Python — Delete Files
Deleting a file
import os
os.remove("old-notes.txt")
# or the modern pathlib way:
from pathlib import Path
Path("old-notes.txt").unlink()
Both raise FileNotFoundError if the file doesn't exist — guard it:
path = Path("cache.tmp")
if path.exists():
path.unlink()
# …or simpler:
path.unlink(missing_ok=True) # Python 3.8+
Deleting an empty folder
os.rmdir("empty-folder") # fails if anything is inside
Path("empty-folder").rmdir() # same rule
Deleting a whole tree — rmtree ⚠️
shutil.rmtree deletes folders recursively and permanently:
import shutil
shutil.rmtree("build-output") # folder + EVERYTHING inside, gone
No recycle bin. No undo. Triple-check the path before running — a stray variable turns cleanup into catastrophe.
The safer habit: send to trash
pip install send2trash
from send2trash import send2trash
send2trash("important-maybe.txt") # → OS Recycle Bin/Trash, recoverable
Scripts that touch user data should trash rather than annihilate.
Common file operations while you're at it
import shutil
shutil.copy("a.txt", "backup/a.txt") # copy file
shutil.copytree("src", "dst") # copy folder tree
shutil.move("draft.md", "published/") # move/rename (also works for folders)
os.rename("old-name.txt", "new-name.txt") # rename only
Path("new-dir").mkdir(exist_ok=True) # make folder; no error if present
Path("deep/nested/dir").mkdir(parents=True, exist_ok=True)
Cleanup pattern: old files only
from pathlib import Path
from time import time
cutoff = time() - 7 * 86400 # older than 7 days
for f in Path("logs").glob("*.log"):
if f.stat().st_mtime < cutoff:
f.unlink(missing_ok=True)
print("removed", f.name)
Glob-filter-stat-delete — the shape of every rotation/cleanup script.
Safety checklist: never delete from user input without validation · prefer
missing_ok=Trueover exists-checks · test scripts on a scratch folder first · print what you're about to remove.
Mini Practice
- Create, then unlink(missing_ok=True) a temp file twice.
- Build a folder tree; delete it with rmtree (on a scratch dir!).
- Install send2trash; trash a file; restore it from your bin.
- mkdir(parents=True) deep path; copy files into it with shutil.
- Write the 7-day log-cleanup script; dry-run by printing first.
Next: NumPy →
Related Topics
Frequently Asked Questions about Delete Files
What is Delete Files in Python?
Delete Files is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Delete Files?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Delete Files.
Why is Delete Files important in Python?
Delete Files is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.