PromptHub
Python Beginner 12 views

Python FileNotFoundError

The code tries to open or access a file or directory that does not exist.

Explanation

FileNotFoundError is a built-in Python exception (subclass of OSError) that occurs when trying to open, read, or access a file or directory that doesn't exist at the specified path. This is common in file processing scripts, configuration loading, and any code that reads from the filesystem. The error message includes the exact path Python tried to access. Note that in Python 2, this was IOError with errno ENOENT.

Common Causes

  • File path typo
  • File doesn't exist
  • Wrong working directory
  • Path separator issues
  • File was moved or deleted

Solution

Check the file path for typos and ensure correct path separators for your OS. Use os.path.exists() or Path.exists() before opening files. Use os.path.join() to construct paths portably instead of string concatenation. Verify the working directory with os.getcwd() if using relative paths. Check file permissions even if the file exists. Use try-except FileNotFoundError for graceful error handling.

Code Example

# FileNotFoundError when file doesn't exist
with open('config.json', 'r') as f:  # FileNotFoundError!
    config = json.load(f)

# Fix: check existence first
import os
if os.path.exists('config.json'):
    with open('config.json', 'r') as f:
        config = json.load(f)
else:
    config = {'default': True}

# Or use try-except
try:
    with open('config.json', 'r') as f:
        config = json.load(f)
except FileNotFoundError:
    config = {'default': True}

# Using pathlib (modern Python)
from pathlib import Path
path = Path('config.json')
if path.exists():
    config = json.loads(path.read_text())

# Check relative paths
print(os.getcwd())  # where are we?
print(os.path.abspath('data/file.csv'))  # full path

# Use os.path.join for portable paths
filepath = os.path.join('data', 'users', 'file.csv')

Error Information

Language

python

Difficulty

Beginner

Views

12

Related Errors