How do I delete a possibly non-empty dir in Python.
The directory may have nested subdirectories many levels deep.
rmtree() is used to delete an entire directory tree, path must point to a directory (but not a symbolic link to a directory). Parameters: path: A path-like object representing a file path.
1 Answer. For removing/deleting any folder that is not empty with Python we have a standard library which is known as shutil. This library provides the function shutil. rmtree() which removes/deletes the non-empty folder.
“delete non empty directory python” Code Answer's os. rmdir('/your/folder/path/') #removes an empty directory. shutil. rmtree('/your/folder/path/') #deletes a directory and all its contents.
Use shutil.rmtree
:
import shutil shutil.rmtree(path)
See the documentation for details of how to handle and/or ignore errors.
The standard library includes shutil.rmtree for this. By default,
shutil.rmtree(path) # errors if dir not empty
will give OSError: [Errno 66] Directory not empty: <your/path>
.
You can delete the directory and its contents anyway by ignoring the error:
shutil.rmtree(role_fs_path, ignore_errors=True)
You can perform more sophisticated error handling by also passing onerrror=<some function(function, path, excinfo)>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With