How to Delete a File in Python
What you’ll build or solve
You’ll delete files in Python using a path, with checks that prevent surprises.
When this approach works best
Deleting a file in Python works well when you:
Learn Python on Mimo
- Clean up temporary downloads, exports, or build artifacts after a script finishes.
- Rotate logs or remove older snapshots to save disk space.
- Remove user-generated files in a local app, like cached thumbnails or reports.
Skip this approach if you need a trash bin or undo behavior. Deleting with Python removes the file immediately, and recovery is not guaranteed.
Prerequisites
- Python 3 installed
- You can run a Python script
- You know what a file path is and how to find the file you want to delete
Step-by-step instructions
1) Delete a file by path
Use pathlib.Path and call .unlink() to delete a file.
Python
from pathlib import Path
path = Path("old_report.txt")
path.unlink()
What to look for: If the file doesn’t exist, .unlink() raises FileNotFoundError. Step 2 shows how to handle that cleanly.
2) Delete only if the file exists
If a missing file should not fail your script, check first or ignore the missing-file error.
Option A: Check with .exists()
Python
from pathlib import Path
path = Path("old_report.txt")
if path.exists():
path.unlink()
Option B: Use missing_ok=True (Python 3.8+)
Python
from pathlib import Path
path = Path("old_report.txt")
path.unlink(missing_ok=True)
What to look for: missing_ok=True only ignores “file not found.” It still raises an error for permissions or if the path is a folder.
3) Handle common delete errors
Deletion can fail for reasons other than “missing file,” like permission issues or trying to delete a directory.
Python
from pathlib import Path
path = Path("old_report.txt")
try:
path.unlink()
except FileNotFoundError:
print("Nothing to delete.")
except PermissionError:
print("No permission to delete this file.")
except IsADirectoryError:
print("This path points to a folder, not a file.")
What to look for: PermissionError often means another program has the file open, common on Windows, or the folder is protected.
Examples you can copy
Example 1: Delete a single temporary file after you read it
Python
from pathlib import Path
tmp = Path("download.tmp")
# ... use the file ...
tmp.unlink(missing_ok=True)
Example 2: Delete all .log files in a folder
Python
from pathlib import Path
logs_dir = Path("logs")
for path in logs_dir.glob("*.log"):
path.unlink()
What to look for: glob("*.log") only matches files in that folder, not subfolders. Use Example 4 for recursive cleanup.
Example 3: Keep the newest 10 files, delete the rest
This pattern works for snapshots, exports, or backups.
Python
from pathlib import Path
folder = Path("snapshots")
files = sorted(
folder.glob("*.json"),
key=lambda p: p.stat().st_mtime,
reverse=True
)
for old_file in files[10:]:
old_file.unlink()
What to look for: st_mtime sorts by last modified time. If your naming includes timestamps, you can also sort by name.
Example 4: Delete matching files recursively
Use rglob() to match files in subfolders too.
Python
from pathlib import Path
root = Path("build")
for path in root.rglob("*.tmp"):
path.unlink()
Example 5: Delete with os.remove() as an alternative
Some codebases use os.remove() for compatibility or to match existing style.
Python
import os
os.remove("old_report.txt")
os.remove() raises the same kinds of errors like FileNotFoundError and PermissionError. You can wrap it in try/except the same way as .unlink().
Common mistakes and how to fix them
Mistake 1: Deleting the wrong file because your path is relative
What you might do:
Python
from pathlib import Path
Path("report.txt").unlink()
Why it breaks: A relative path deletes report.txt in your current working folder, which may not be your script’s folder.
Correct approach: Anchor to the script location
Python
from pathlib import Path
base = Path(__file__).parent
path = base / "report.txt"
path.unlink()
Mistake 2: Trying to delete a folder with file deletion APIs
What you might do:
Python
from pathlib import Path
Path("logs").unlink()
Why it breaks: .unlink() deletes files, not directories. Python raises IsADirectoryError.
Correct approach: Delete an empty folder
Python
from pathlib import Path
Path("logs").rmdir()
If you need to delete a folder and everything inside it:
Python
import shutil
shutil.rmtree("logs")
Use shutil.rmtree() with care because it removes the folder contents too.
Mistake 3: Assuming “missing file” is always an error
What you might do:
Python
from pathlib import Path
Path("old_report.txt").unlink()
Why it breaks: The file might already be gone, which raises FileNotFoundError.
Correct approach:
Python
from pathlib import Path
Path("old_report.txt").unlink(missing_ok=True)
Or check first:
Python
from pathlib import Path
p = Path("old_report.txt")
if p.exists():
p.unlink()
Troubleshooting
If you see FileNotFoundError, confirm the path points to the file you expect, then decide if “already deleted” should count as success.
If you see PermissionError, close programs that might have the file open, then try again. On Windows, editors and terminals can hold locks.
If you see IsADirectoryError, you passed a folder path. Use .rmdir() for empty folders or shutil.rmtree() for a folder tree.
If nothing gets deleted in a cleanup loop, print the matched paths to confirm your glob pattern:
Python
from pathlib import Path
for p in Path("logs").glob("*.log"):
print(p)
Quick recap
- Delete a file with
Path("name").unlink(). - Use
missing_ok=Trueor.exists()when “missing” should not fail the script. - Catch
PermissionErrorandIsADirectoryErrorfor common issues. - Use
glob()for folder cleanup andrglob()for recursive cleanup. - Anchor paths to
Path(__file__).parentwhen you need predictable targets.
Join 40M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot