Python FileNotFoundError — Path Resolution Guide

Fix Python FileNotFoundError. Learn about relative vs absolute paths, pathlib, working directory issues, and cross-platform path handling.

Python Exceptions

Detailed Explanation

Python FileNotFoundError

FileNotFoundError is raised when you try to open, read, or access a file or directory that does not exist. It is a subclass of OSError.

Basic Example

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

Why It Happens

The most common cause is using a relative path that resolves differently depending on where you run the script from:

# project/
#   src/
#     app.py    <- opens "config.yaml"
#   config.yaml

cd project && python src/app.py     # Works: CWD is project/
cd project/src && python app.py     # Fails: CWD is project/src/

Solutions

1. Use file-relative paths:

from pathlib import Path

# Get directory of current script
BASE_DIR = Path(__file__).resolve().parent

# Build paths relative to the script
config_path = BASE_DIR / ".." / "config.yaml"
# Or
config_path = BASE_DIR.parent / "config.yaml"

with open(config_path) as f:
    data = f.read()

2. Use pathlib (modern Python):

from pathlib import Path

path = Path("data/output.csv")

# Check before accessing
if path.exists():
    content = path.read_text()

# Create parent directories
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("data")

3. Cross-platform paths:

# Bad: hardcoded separator
path = "data\\files\\output.csv"  # Fails on Linux/macOS

# Good: use pathlib or os.path.join
from pathlib import Path
path = Path("data") / "files" / "output.csv"

import os
path = os.path.join("data", "files", "output.csv")

Debugging Checklist

import os
from pathlib import Path

# 1. What is the current working directory?
print(os.getcwd())

# 2. Does the file exist?
print(Path("config.yaml").exists())

# 3. What is the absolute path being accessed?
print(Path("config.yaml").resolve())

# 4. List files in directory
print(list(Path(".").iterdir()))

Best Practices

  1. Always use pathlib.Path for path operations
  2. Use __file__-relative paths for project resources
  3. Check existence before access for optional files
  4. Create directories with mkdir(parents=True, exist_ok=True)
  5. Use os.path.join() or Path / operator for cross-platform code

Use Case

FileNotFoundError is extremely common during file processing, configuration loading, and deployment. The working directory issue (relative paths resolving differently depending on where the script is run) is a frequent source of bugs in CI/CD pipelines, Docker containers, and scheduled tasks. Understanding pathlib and __file__-relative paths prevents these issues.

Try It — Error Code Reference

Open full tool