Python
File Handling
Error Handling
Best Practices
Programming

Most pythonic way to delete a file which may not exist

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

The most Pythonic way to delete a file that may not exist is to attempt the deletion and handle the "not found" case explicitly. This follows the EAFP style: easier to ask forgiveness than permission. It is cleaner and safer than checking first, because an existence check and a delete operation are two separate steps that can race with each other.

Use try and except FileNotFoundError

The classic pattern is simple:

python
1import os
2
3path = "report.txt"
4
5try:
6    os.remove(path)
7except FileNotFoundError:
8    pass

This is Pythonic because it expresses the real operation directly. The code tries to remove the file and ignores only the specific case that is acceptable.

Why exists() Before remove() Is Weaker

Many beginners write this instead:

python
1import os
2
3if os.path.exists("report.txt"):
4    os.remove("report.txt")

This looks reasonable, but it has a race condition. Another process could delete the file after exists() returns True and before remove() runs. That means you still need exception handling if the code must be correct under concurrency.

So the check does not really simplify the logic. It often just adds another filesystem call.

pathlib Is a Clean Modern Alternative

If you already use pathlib, the equivalent style is more readable.

python
1from pathlib import Path
2
3path = Path("report.txt")
4
5try:
6    path.unlink()
7except FileNotFoundError:
8    pass

On Python 3.8 and newer, unlink also supports missing_ok=True:

python
from pathlib import Path

Path("report.txt").unlink(missing_ok=True)

That is concise and still expresses the exact intent.

Remember the Difference Between Files and Directories

The advice here is specifically about deleting files. If the target may be a directory, use the correct API instead of assuming one delete call covers both cases.

python
1from pathlib import Path
2
3path = Path("old-output")
4
5if path.is_dir():
6    print("directory cleanup needs a directory-specific strategy")

That distinction matters because a Pythonic file-deletion pattern should still be precise about what kind of filesystem object it is removing.

Do Not Swallow Unrelated Errors

The important detail is to catch only FileNotFoundError. If you write a broad except OSError or bare except, you may accidentally hide real problems such as:

  • permission issues
  • trying to delete a directory instead of a file
  • invalid path problems

That is too much silence for a cleanup operation that may matter.

python
1from pathlib import Path
2
3path = Path("/protected/report.txt")
4
5try:
6    path.unlink()
7except FileNotFoundError:
8    pass

If the file exists but cannot be deleted because of permissions, the exception should still surface.

Use the Right Style for the Call Site

For one-off cleanup code, try and except FileNotFoundError is usually ideal. For utility functions, Path.unlink(missing_ok=True) is often the most expressive if your Python version supports it.

The key principle is always the same: treat missing files as one accepted outcome, not as a condition you must predict before acting.

If your code runs across multiple Python versions, it is worth choosing one style consistently so your cleanup helpers behave the same everywhere. A tiny helper function can hide the version difference without hiding real filesystem errors.

Common Pitfalls

  • Checking exists() before deleting and thinking that removes all race conditions.
  • Catching Exception or OSError and hiding real filesystem errors.
  • Using unlink(missing_ok=True) on older Python versions where it is unsupported.
  • Forgetting that os.remove is for files, not directories.
  • Writing extra conditional logic when one narrow exception handler would be clearer.

Summary

  • The Pythonic pattern is to attempt deletion and catch FileNotFoundError.
  • This is better than an exists() check because it avoids a race-prone two-step flow.
  • 'pathlib.Path.unlink() is a clean modern API for file deletion.'
  • 'missing_ok=True is a concise option on newer Python versions.'
  • Catch only the missing-file case so real errors remain visible.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.