Python (Scripting) - Remove directory using os.rmdir

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
There are three similar Python modules that can be used to remove a directory.
- os.rmdir (this article) - 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 - remove parent and child directories (will remove even if directory is not empty)
Here is the minimal boilterplate code without error handling to remove the /usr/local/foo directory using os.rmdir.
#!/usr/bin/python3
import os
os.rmdir("/usr/local/foo")
Here is a more practical example, with try/except/else error handling.
#!/usr/bin/python3
import os
directory = "/usr/local/foo"
if not os.path.exists(directory):
print(f"{directory} does not exists")
else:
try:
os.rmdir(directory)
except Exception as exception:
print(f"got the following exception when attempting to rmdir {directory} - {exception}")
else:
print(f"successfully removed directory {directory}")
Be aware that if the target directory contains files or directories, the removal will fail and something like this will be returned. For this reason, I almost always instead use shutil.rmtree to remove a directory.
[Errno 39] Directory not empty: '/usr/local/foo'
Did you find this article helpful?
If so, consider buying me a coffee over at