Python Delete Files
Tutorial 37 of 65 · pythondeck.com Python course
Use os.remove/os.unlink to delete a single file, os.rmdir for an empty directory, shutil.rmtree for a directory tree. pathlib.Path.unlink is the object-oriented equivalent.
Deleting removes paths from the filesystem—irreversibly on many systems unless you use a recycle step or backups. pathlib.Path.unlink() removes files; shutil.rmtree removes directory trees. Know the difference between deleting a file and deleting a directory that still contains files.
Scripts that "clean up" build artefacts or temp dirs need guards so a wrong path does not wipe a home directory. Prefer explicit roots and confirmation for destructive CLI flags.
Path.unlink() and missing_ok=True (Python 3.8+).
os.remove and os.unlink (same underlying operation for files).
shutil.rmtree for non-empty directories.
Checking is_file vs is_dir before choosing the API.
Symlinks: unlink removes the link, not the target (usually desired).
Recycle patterns: move to trash folder before permanent delete when UX requires it.
There is no standard "trash" in the stdlib—desktop apps use platform APIs. For idempotent cleanup, unlink(missing_ok=True) avoids race-prone check-then-delete sequences.
On Unix, a file open by another process can be unlinked while the descriptor stays valid until closed. On Windows, open files often block deletion—handle PermissionError with retry or user messaging.
Rotate logs by renaming then deleting old files, or use logging.handlers.RotatingFileHandler instead of manual deletes in long-running services.
Passing user input directly into rmtree without validating the path.
Using unlink on a directory (raises IsADirectoryError).
Assuming rmtree is undoable—it is not.
Deleting symlinks with rmtree on the target side unintentionally.
Race conditions: file recreated between check and delete.
Resolve paths and ensure deletes stay under an allowed base directory.
Use missing_ok=True for idempotent cleanup scripts.
Require --force or typed confirmation for destructive CLI operations.
Prefer logging rotation and tempfile contexts over ad-hoc mass deletes.
Re-read the examples below with these ideas in mind; change variable names and inputs to match your own project.
The program below demonstrates remove file. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Example: Remove file
# Run in the REPL or save as a .py file and execute with python.
import os
if os.path.exists("out.json"):
os.remove("out.json")
This sample walks through pathlib in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# Example: pathlib
# Run in the REPL or save as a .py file and execute with python.
from pathlib import Path
p = Path("out.json")
p.unlink(missing_ok=True)
Here is a hands-on illustration of rmtree. Follow the inline comments first; only then execute the snippet and compare the result with what you expected.
# Example: rmtree
# Run in the REPL or save as a .py file and execute with python.
import shutil, os
os.makedirs("tmp/sub", exist_ok=True)
shutil.rmtree("tmp")
The program below demonstrates remove file. Read the comments on each line, run the code, then change names or values to see how the output shifts.
# Deleting files is irreversible — check existence first
from pathlib import Path # path objects
temp = Path("out.txt") # file created earlier
if temp.exists(): # guard against missing path
temp.unlink() # delete file
print("removed", temp) # confirmation
else: # nothing to delete
print("already gone") # safe message
missing = Path("nope.bin") # guaranteed absent
print(missing.exists()) # False
try: # optional strict delete
missing.unlink() # raises FileNotFoundError
except FileNotFoundError: # handle gracefully
print("not found — skipped") # expected path
This sample walks through rmtree folder in a small, runnable script. Paste it into the REPL or save it as a .py file before you continue to the next block.
# shutil.rmtree removes directories recursively
import shutil # tree removal
from pathlib import Path # paths
folder = Path("data") # directory from earlier examples
if folder.exists(): # only remove when present
shutil.rmtree(folder) # delete folder + contents
print("folder deleted") # log action
folder.mkdir() # recreate empty dir for later demos
print(folder.exists()) # True again
child = folder / "tmp.txt" # nested file
child.write_text("x", encoding="utf-8") # create
child.unlink() # delete single file inside
print(list(folder.iterdir())) # empty directory