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 theonerror
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')
Output:


Note:
By default, The shutil.rmtree()
will fail to delete the directory containing any read-only files.
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.
Example:
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.
Example:
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)
Leave a Reply