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.

Easy Python 3.9+ Aug 9, 2026 Files & data 15 views 0 copies

Python code

24 lines
Python 3.9+
from 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

stdout
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

  1. Use `path.unlink(missing_ok=True)` in Python 3.8+ to skip the existence check entirely
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.