Python (Scripting) - Remove directory using shutil.rmtree

by
Jeremy Canfield |
Updated: July 22 2024
| Python (Scripting) articles
There are three similar Python modules that can be used to remove a directory.
- os.rmdir - remove a single directory (will fail if the directory is not empty)
- os.removedirs - remove parent and child directories (will fail if the directory is not empty)
- shutil.rmtree (this article) - remove parent and child directories (will remove even if directory is not empty)
Here is the minimal boilterplate code without error handling to remove all of the files and directories at and below the /usr/local/foo directory using shutil.rmtree. The directory and all of the files at and below the directory will be removed.
#!/usr/bin/python3
import shutil
shutil.rmtree("/usr/local/foo")
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python3
import shutil
directory = "/usr/local/foo"
if not os.path.exists(directory):
print(f"{directory} does not exists")
else:
try:
shutil.rmtree(directory)
except Exception as exception:
print(f"got the following exception when attempting to rmdir {directory} - {exception}")
else:
print(f"successfully removed directory {directory}")
Did you find this article helpful?
If so, consider buying me a coffee over at