In Python 3.8 and later, call Path.unlink(missing_ok=True) to remove a file if it exists and ignore it if it is already absent:
from pathlib import Path
Path("file.txt").unlink(missing_ok=True)
For Python versions before 3.8, catch FileNotFoundError around the deletion instead.
Use missing_ok=True in Python 3.8 and later
Path.unlink() removes the file or symbolic link at the given path. Its default is missing_ok=False, so an absent path raises FileNotFoundError. Set missing_ok=True to treat an already-missing path as an ordinary outcome. The parameter was added in Python 3.8; see the Python 3.11.17 pathlib documentation.
from pathlib import Path
Path("file.txt").unlink(missing_ok=True)
Use FileNotFoundError handling on older Python
For compatibility with Python versions before 3.8, catch only the exception that means the target is missing:
#1 Best Overall
from pathlib import Path
try:
Path("file.txt").unlink()
except FileNotFoundError:
pass
The same pattern works with os.remove(path) or os.unlink(path). Catching FileNotFoundError rather than every OSError leaves permission failures and other filesystem errors visible. Choose the API that fits the rest of your code.
Choose the approach that fits your code
| Approach | Python support | When the file is absent | Best fit |
|---|---|---|---|
Path.unlink(missing_ok=True) |
Python 3.8 and later | Silently ignored | Concise deletion when absence needs no special handling |
try/except FileNotFoundError |
Works as a compatibility pattern, including before Python 3.8 | The handler can do nothing or run custom logic | Older Python or when absence requires a specific response |
Do not use file deletion to remove a directory
Path.unlink() removes a file or symbolic link, not a directory tree. To remove an empty directory, use Path.rmdir(); it raises an error if the directory is not empty. The pathlib documentation describes these path operations.
Quick Recap
Best Value
Rank #2
Handle paths and filesystem errors carefully
- A relative path such as
file.txtis resolved from the process’s current working directory. Use the intended path if the file is elsewhere. - A separate
exists()check cannot guarantee that deletion will succeed: the filesystem may change between the check and the removal. Attempt deletion directly and handleFileNotFoundErrorif absence is expected. missing_ok=Trueonly suppresses the missing-file case. It does not make deletion succeed when permissions or another operating-system error prevents it.
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




