How to Delete a File if it Exists in Python
Delete a file safely in Python using pathlib's Path.unlink, checking existence first to avoid errors.
Python code
24 linesfrom pathlib import Path
def delete_file_if_exists(file_path: str) -> bool:
"""Delete a file if it exists. Returns True if deleted, False if not found."""
path = Path(file_path)
if path.exists():
path.unlink()
print(f"Deleted: {path}")
return True
else:
print(f"File not found: {path}")
return False
if __name__ == "__main__":
# Example: create a temp file, then delete it
import tempfile
test_file = Path(tempfile.gettempdir()) / "example_delete.txt"
test_file.write_text("Temporary content")
# Delete the file
delete_file_if_exists(test_file)
# Try deleting again (file no longer exists)
delete_file_if_exists(test_file)
Output
Deleted: /tmp/example_delete.txt
File not found: /tmp/example_delete.txt
How it works
The Path.exists() check determines whether the file currently exists. If it does, unlink() removes it and the function returns True. For a non-existent file, it prints a message and returns False. Using pathlib handles file paths consistently across operating systems. The tempfile module creates a temporary file for demonstration. On second call, the file is already removed, so exists() returns False.
Common mistakes
- Using Path.unlink() without checking existence, which raises FileNotFoundError
- Confusing Path.unlink() with Path.rmdir() for directories instead of files
- Not converting string paths to Path objects before calling methods
Variations
- Use `path.unlink(missing_ok=True)` in Python 3.8+ to skip the existence check entirely
- Wrap in try/except FileNotFoundError as an alternative to existing check
Real-world use cases
- Cleaning up temporary files created during automated test runs.
- Removing stale cache files before regenerating data in a pipeline.
- Deleting uploads in a web app when a user cancels their request.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.