How to Delete a File in Python with Path.unlink
Programs make files they later need to get rid of: a draft, a temporary export, a database to rebuild from scratch. Path.unlink() deletes one, and its missing_ok option makes "delete it if it's there" a single line. This guide creates a file, deletes it and deletes it again, with real output from Python 3.15.2.
Syntax
from pathlib import Path
Path(<file path>).unlink()
Path(<file path>).unlink(missing_ok=True)
| Part | What it means |
|---|---|
Path(<file path>) | The file to delete |
.unlink() | Deletes it. Raises FileNotFoundError if it isn't there |
missing_ok=True | A file that's already gone isn't an error |
Python's pathlib documentation: "Remove this file or symbolic link. If the path points to a directory, use Path.rmdir() instead. If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist."
Prerequisites
- uv and Python. This guide uses uv 0.13.10 with Python 3.15.2, in a project made with
uv init.
Step 1: Write the Script
from pathlib import Path
draft = Path("draft.txt")
draft.write_text("first draft", encoding="utf-8")
print("Exists:", draft.exists())
draft.unlink()
print("Exists after unlink:", draft.exists())
draft.unlink(missing_ok=True)
print("The second unlink, with missing_ok=True, raised nothing.")

write_text()createsdraft.txt, so there's a file to delete.- The first
unlink()deletes it. - The second
unlink()targets a file that no longer exists, withmissing_ok=True.
Step 2: Run It
uv run python delete_file.py
Exists: True
Exists after unlink: False
The second unlink, with missing_ok=True, raised nothing.

The file existed, unlink() removed it, and the second call found nothing to delete and carried on quietly. That's the "delete it if it's there" pattern, with no exists() check needed.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
unlink() on a file that isn't there, without missing_ok | FileNotFoundError: [Errno 2] No such file or directory: 'nope.txt' | Pass missing_ok=True when a missing file is fine |
unlink() on a folder | On macOS: PermissionError: [Errno 1] Operation not permitted: 'adir' | Use Path.rmdir() for an empty folder |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
FileNotFoundError from unlink() | The path is wrong, or the file was already deleted | Check the path, or pass missing_ok=True |
FAQ
Does unlink() move the file to the Trash?
No. It deletes the file for good, so double-check the path before you call it.
Since when does missing_ok exist?
Python 3.8. The documentation: "Changed in version 3.8: The missing_ok parameter was added."
Conclusion
draft.unlink() deleted the file, and draft.unlink(missing_ok=True) then did nothing, without an error, because the file was already gone.
Additional Resources
- Path.unlink — deleting a file or symbolic link.
- Path.rmdir — deleting an empty folder.
