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")
Note: Deleting a file is permanent. os.remove does not move the file to a recycle bin or trash, so there is no easy undo. Be sure of the path before you run it.

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.

FunctionRemovesNotes
os.remove(path)A single fileErrors if the path is a directory or missing
os.rmdir(path)An empty directoryErrors if the directory still has contents
shutil.rmtree(path)A directory and everything inside itFrom the shutil module; use with great care
  • 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.
Note: shutil.rmtree removes a directory and all of its contents recursively without confirmation. Double check the target path, since a wrong value can wipe out far more than you intended.