Delete files and directories in Python
Choose unlink, rmdir, or shutil.rmtree for the correct target, handle missing paths and symlinks, and understand when deletion bypasses the trash.
Use Path.unlink() or os.remove() for a file or symbolic link. Use Path.rmdir() or os.rmdir() for an empty directory, and shutil.rmtree() to remove a directory tree and its contents. These standard-library operations do not move items to the system trash.
Delete a file
These are alternative forms; replace the example path with the intended file:
from pathlib import Path
Path("output/report.txt").unlink()
import os
os.remove("output/report.txt")
A missing file raises FileNotFoundError. On Python 3.8 and later, Path("output/report.txt").unlink(missing_ok=True) ignores that specific missing-file condition. It does not ignore permission failures or treat a directory as a regular file.
Delete an empty directory
from pathlib import Path
Path("output/empty-folder").rmdir()
os.rmdir() provides the same kind of operation. A nonempty directory causes an OSError; remove its contents only if that is actually intended.
Delete a directory tree
from pathlib import Path
import shutil
folder = Path("output/disposable-build")
print(folder.absolute()) # Inspect the intended location before running deletion.
# After confirming the target:
shutil.rmtree(folder)
There is no built-in undo. Printing a path helps inspection but does not validate it or defend against concurrent filesystem changes. Keep destructive paths narrowly scoped, especially when any portion comes from user input.
| Operation | Target |
|---|---|
unlink() / os.remove() |
A file or symlink; unlinking a symlink removes the link |
rmdir() / os.rmdir() |
An empty directory |
shutil.rmtree() |
A directory tree, not a top-level symlink to a directory |
FAQ
Can I check the target first? Path.is_file() and Path.is_dir() help inspect it, but both follow symlinks. Check is_symlink() first when link handling matters. A precheck does not guarantee that the target stays unchanged until deletion, so still handle operation errors.
Can I send it to the trash? A third-party package such as Send2Trash uses supported platform trash facilities. That is different from permanent standard-library deletion; availability and recovery depend on the platform and filesystem.
Why do I get PermissionError? Check directory permissions and ownership, filesystem restrictions, and open handles. Windows commonly prevents deleting files held open without suitable sharing permissions. Do not assume elevating privileges is the right fix.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan