Удаление пустых папок python

Python Remove/Delete Non-Empty Folder

Are you getting OSError the directory is not empty error when deleting a non-empty folder using the os.rmdir() method? The os.rmdir() method is helpful to delete only empty folders.

In this article, we will use the shutil module to remove the non-empty directory or folder. The directory may have nested subdirectories many levels deep.

Shutil rmtree() to Delete Non-Empty Directory

The shutil module offers various methods to perform high-level operations on files and collections of files, such as file copying and file removal in Python.

Here we will see how to delete non-empty directories or folders in Python using the shutil.rmtree(‘path’) function.

shutil.rmtree(path, ignore_errors=False, onerror=None)
  • The rmtree(‘path’) deletes an entire directory tree (including subdirectories under it).
  • The path must point to a directory (but not a symbolic link to a directory).
  • Set ignore_errors to True if you want to ignore the errors resulting from failed removal. Please set it to False to know the reason behind failed removal.
  • If the ignore_errors parameter is omitted, you need to handle errors using try-except by calling a handler specified by the onerror class.

Example

Let’s see how to delete a non-empty ‘account’ folder present in our drive.

import shutil # remove old account directory shutil.rmtree(r'E:\demos\files_demos\accounts_old')

Before deleting non empty folder

After deleting non empty folder

By default, The shutil.rmtree() will fail to delete the directory containing any read-only files .

Читайте также:  Inheriting classes in java

It will throw a PermissionError if a folder contains any read-only files. Set the optional argument ignore_errors to True to remove the remaining folder contents.

import shutil # remove old account directory shutil.rmtree(r'E:\demos\files_demos\accounts_old', ignore_errors=True)

Also, If files are added concurrently to this directory, then rmtree() will fail.

Delete Non-Empty Directory with Read-Only Files

  • As we discussed, The shutil.rmtree() will fail to delete the directory containing any read-only files.
  • Note: ignore_errors=True does not guarantee the directory will be deleted. There could be a PermissionError.
  • If you set ignore_errors to True, it will delete all other files except read-only files from a directory. (Directory is still present but only with read-only files).
  • Set ignore_errors to False to know the reasons behind failed removals.

Use the onerror parameter of a shutil.rmtree() function to delete an entire directory that contains some read-only files.

We need to write a custom function and assign it to the onerror parameter. This custom function uses the onerror callback to clear the read-only bit from a read-only file and again reattempt the remove.

import os import shutil import stat # remove directory with read-only files def rm_dir_readonly(func, path, _): "Clear the readonly bit and reattempt the removal" os.chmod(path, stat.S_IWRITE) func(path) shutil.rmtree(r'E:\demos\files_demos\accounts_old', onerror=rm_dir_readonly) 

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Удаление непустой папки с помощью Python

Чтобы удалить непустую папку в Python, можно использовать модуль shutil , который предоставляет функции для копирования и удаления файлов и каталогов.

ВНИМАНИЕ! В этом руководстве показано, как навсегда удалить файлы и каталоги. Убедитесь, что вы ввели пути к файлам правильно, чтобы быть на 100% уверенным, что удалите только те каталоги, которые хотите удалить.

Чтобы удалить каталог и все его содержимое, включая любые подкаталоги и файлы, можно воспользоваться функцией rmtree .

import shutil # Replace with the path to the directory you want to remove directory = '/path/to/directory' shutil.rmtree(directory)

Это приведет к удалению каталога и всего его содержимого, включая все подкаталоги и файлы. Обратите внимание, что этот подход не удаляет файлы, доступные только для чтения! Вместо этого вы увидите ошибку.

Давайте рассмотрим несколько альтернативных подходов к удалению непустых папок с помощью Python.

Альтернативные подходы

Функция os.walk()

Чтобы удалить непустую папку в Python, можно удалить файлы по отдельности с помощью функции os.walk .

Вот как это выглядит в коде:

import os # Replace with the path to the directory you want to remove directory = '/path/to/directory' # Use os.walk to traverse the directory tree for root, dirs, files in os.walk(directory): # For each file in the directory for file in files: # Construct the full path to the file file_path = os.path.join(root, file) # Delete the file os.remove(file_path) # For each subdirectory in the directory for dir in dirs: # Construct the full path to the subdirectory dir_path = os.path.join(root, dir) # Delete the subdirectory os.rmdir(dir_path) # Delete the top-level directory os.rmdir(directory)

Этот код использует функцию os.walk для перебора дерева каталогов и удаления каждого файла и подкаталога по указанному пути. После удаления всех файлов и подкаталогов удаляется и каталог верхнего уровня.

Модуль pathlib

Чтобы удалить непустую папку в Python с помощью модуля pathlib , вы можете использовать следующий код:

import pathlib # A recursive function to remove the folder def del_folder(path): for sub in path.iterdir(): if sub.is_dir(): # Delete directory if it's a subdirectory del_folder(sub) else : # Delete file if it is a file: sub.unlink() # This removes the top-level folder: path.rmdir() # Example use del_folder(pathlib.Path('path/to/folder'))

Этот код использует метод iterdir для перебора дерева каталогов и удаления каждого файла и подкаталога в указанном каталоге. После удаления всех файлов и подкаталогов удаляется и каталог верхнего уровня.

Спасибо за прочтение. Счастливого кодинга!

Источник

Как удалить только пустые папки в Python?

bestprogrammer.ru

Могу ли я стать полноценным разработчиком Python

Программирование и разработка

В этой статье мы увидим, как удалять только пустые папки в Python.

Перед удалением папки вот изображение, показывающее файлы внутри основного каталога.

Перед удалением папки вот изображение, показывающее

Как показано на изображении выше, в папке есть 2 пустых подпапки и 1 непустая папка.

Итак, после запуска кода эти 2 папки должны быть удалены.

С помощью модуля ОС

С помощью модуля мы можем легко получить файлы любой директории.

С помощью модуля мы можем легко получить файлы

Используя loop

В этом методе мы будем использовать цикл для поиска содержимого внутри каждой папки. Затем, если папка пуста, мы ее удалим.

All Folder -> (‘C:\\Users\\Untitled Folder\\.ipynb_checkpoints’, [], [‘Untitled-checkpoint.ipynb’]) All Folder -> (C:\\Users\\Untitled Folder\\Empty Folder 1′, [], []) All Folder -> (‘C:\\Users\\Untitled Folder\\Empty Folder 2’, [], []) All Folder -> (‘C:\\Users\\Untitled Folder\\Non empty folder’, [], [‘untitled.txt’]) В этом методе мы будем использовать цикл для поиска содержимого

Источник

jacobtomlinson / remove_empty_folders.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

#! /usr/bin/env python
»’
Module to remove empty folders recursively. Can be used as standalone script or be imported into existing script.
»’
import os , sys
def removeEmptyFolders ( path , removeRoot = True ):
‘Function to remove empty folders’
if not os . path . isdir ( path ):
return
# remove empty subfolders
files = os . listdir ( path )
if len ( files ):
for f in files :
fullpath = os . path . join ( path , f )
if os . path . isdir ( fullpath ):
removeEmptyFolders ( fullpath )
# if folder empty, delete it
files = os . listdir ( path )
if len ( files ) == 0 and removeRoot :
print «Removing empty folder:» , path
os . rmdir ( path )
def usageString ():
‘Return usage string to be output in error cases’
return ‘Usage: %s directory [removeRoot]’ % sys . argv [ 0 ]
if __name__ == «__main__» :
removeRoot = True
if len ( sys . argv ) < 1 :
print «Not enough arguments»
sys . exit ( usageString ())
if not os . path . isdir ( sys . argv [ 1 ]):
print «No such directory %s» % sys . argv [ 1 ]
sys . exit ( usageString ())
if len ( sys . argv ) == 2 and sys . argv [ 2 ] != «False» :
print «removeRoot must be ‘False’ or not set»
sys . exit ( usageString ())
else :
removeRoot = False
removeEmptyFolders ( sys . argv [ 1 ], removeRoot )

Источник

Оцените статью