error python

Python FileNotFoundError

Understanding Python FileNotFoundError - raised when trying to open or access a file that does not exist at the specified path.

What It Means

FileNotFoundError (a subclass of OSError) is raised when trying to open, read, or perform operations on a file or directory that does not exist. The error message reads: [Errno 2] No such file or directory: 'filename'.

Common Causes

  • Typo in the file path
  • Using a relative path when the working directory is different than expected
  • File hasn’t been created yet
  • File was deleted or moved
  • Path separators wrong for the operating system
  • Missing directory in the path
  • Environment-specific paths (works on dev machine, fails in production)

How to Fix

Use pathlib for reliable paths

from pathlib import Path

# Build paths relative to the script location
BASE_DIR = Path(__file__).resolve().parent
config_path = BASE_DIR / "config" / "settings.json"

# Check if the file exists
if config_path.exists():
    data = config_path.read_text()
else:
    print(f"File not found: {config_path}")

Use os.path for cross-platform paths

import os

# Build cross-platform paths
base_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(base_dir, "config", "settings.json")

# Check existence
if os.path.isfile(config_path):
    with open(config_path) as f:
        data = f.read()

Handle the error gracefully

try:
    with open("data.csv") as f:
        data = f.read()
except FileNotFoundError:
    print("data.csv not found. Using default data.")
    data = "default,data"

Debug the path

import os

path = "config/settings.json"

# Check current working directory
print(f"Current directory: {os.getcwd()}")
print(f"File exists: {os.path.exists(path)}")
print(f"Absolute path: {os.path.abspath(path)}")

# List files in the expected directory
if os.path.exists("config"):
    print(f"Files in config/: {os.listdir('config')}")
else:
    print("config/ directory doesn't exist")

Create the file/directory if missing

from pathlib import Path

# Create directories if they don't exist
output_dir = Path("output/reports")
output_dir.mkdir(parents=True, exist_ok=True)

# Create a file with default content if it doesn't exist
config_file = Path("config.json")
if not config_file.exists():
    config_file.write_text('{"debug": false}')

Fix common path issues

# Wrong: hardcoded path separator
path = "data\\file.csv"  # Works on Windows only

# Right: use os.path.join or pathlib
from pathlib import Path
path = Path("data") / "file.csv"  # Works everywhere

# Wrong: relative path from wrong directory
# Running `python scripts/process.py` from project root
# Inside process.py: open("data/input.csv")
# This looks for data/input.csv relative to where you ran python

# Right: use path relative to script
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
data_path = os.path.join(script_dir, "..", "data", "input.csv")

Fix in Docker or production

# Use environment variables for paths
import os

data_dir = os.environ.get("DATA_DIR", "/app/data")
config_path = os.path.join(data_dir, "config.json")