Python Error

FileNotFoundError

FileNotFoundError is raised when trying to open or access a file or directory that doesn't exist. It's a subclass of OSError and has errno set to ENOENT.

Common causes

  • File path is incorrect or has a typo
  • File was moved, renamed, or deleted
  • Using relative path from wrong working directory
  • Missing file extension in the path
  • Permission issue masquerading as file not found

How to fix it

  • Use os.path.exists() or Path.exists() to check before opening
  • Use absolute paths or Path(__file__).parent for reliable paths
  • Use try/except FileNotFoundError for graceful handling
  • Use pathlib.Path for cross-platform path handling
  • Log the full path when errors occur for easier debugging

Example

FileNotFoundError example
# Error example
with open("data.csv") as f:
    content = f.read()
# FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

# Fix: check existence first
from pathlib import Path

file_path = Path("data.csv")
if file_path.exists():
    content = file_path.read_text()

# Fix: use try/except
try:
    with open("data.csv") as f:
        content = f.read()
except FileNotFoundError:
    print("File not found, using defaults")
    content = ""

# Fix: use path relative to script
script_dir = Path(__file__).parent
data_file = script_dir / "data.csv"

Track FileNotFoundError with Checkend

Checkend automatically captures FileNotFoundError errors in your Python application with full context:

  • Complete traceback with syntax highlighting
  • Request context (URL, params, headers)
  • Automatic grouping of similar errors
  • Instant notifications when errors occur

Stop debugging in production

Get full error context and fix issues faster with self-hosted error tracking.