Python Delete Files
To remove files and folders from disk, Python relies on the built-in os module and its companion functions for deleting paths safely.
Deleting files with the os module
Python does not delete files through the open function. Instead you use the os module, part of the standard library, which provides functions for interacting with the operating system. To remove a single file you call os.remove and pass the path. The related os.rmdir removes an empty folder.
Removing a single file
import os
os.remove("report.txt")
print("File deleted")Check before you delete
Calling os.remove on a path that does not exist raises FileNotFoundError. A common and safer pattern is to check that the file exists first with os.path.exists, or to wrap the removal in a try and except so a missing file does not crash your program.
Deleting only if the file exists
import os
path = "report.txt"
if os.path.exists(path):
os.remove(path)
print("Deleted", path)
else:
print("Nothing to delete")Deleting with error handling
import os
try:
os.remove("maybe_missing.txt")
print("File removed")
except FileNotFoundError:
print("File was not there")
except PermissionError:
print("No permission to delete this file")Functions for removing paths
Different situations call for different functions. Removing a lone file, an empty directory, and a directory full of content each has its own tool, and using the wrong one raises an error.
- Import os before calling remove, rmdir, or path helpers.
- os.remove works on files, while os.rmdir works only on empty folders.
- To delete a folder that still holds files, use shutil.rmtree from the shutil module.
- Guard deletions with os.path.exists or a try and except to avoid crashes.