High severity beginner · Fix: 2-5 min

FileNotFoundError

builtins.FileNotFoundError

What this error means
Python raises FileNotFoundError when attempting to open a text editor file path that does not exist or is incorrect.

Stack trace

traceback
Traceback (most recent call last):
  File "example.py", line 5, in <module>
    with open('nonexistent.txt', 'r') as f:
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'
QUICK FIX
Wrap file open calls in try/except FileNotFoundError and verify file paths before access.

Why it happens

This error occurs because the specified file path does not exist on the filesystem or the path is misspelled. The open() function in Python requires the file to exist when opening in read mode.

Detection

Check file existence with os.path.exists() before opening or catch FileNotFoundError exceptions to log missing file paths before the program crashes.

Causes & fixes

1

The file path is misspelled or incorrect.

✓ Fix

Verify and correct the file path string to match the exact location and filename on disk.

2

The file does not exist at the specified location.

✓ Fix

Create the file before opening it in read mode or check for existence and handle the missing file case.

3

Relative path is used but the working directory is different than expected.

✓ Fix

Use absolute file paths or ensure the working directory is set correctly before opening the file.

Code: broken vs fixed

Broken - triggers the error
python
with open('myfile.txt', 'r') as f:  # This line raises FileNotFoundError if file missing
    content = f.read()
    print(content)
Fixed - works correctly
python
import os
filename = 'myfile.txt'
if os.path.exists(filename):  # Check file existence before opening
    with open(filename, 'r') as f:
        content = f.read()
        print(content)
else:
    print(f"File not found: {filename}")
Added os.path.exists() check to verify the file exists before opening to prevent FileNotFoundError.

Workaround

Catch FileNotFoundError in a try/except block and provide a fallback such as creating the file or notifying the user.

Prevention

Use absolute paths and verify file existence programmatically before file operations to avoid runtime errors.

Python 3.6+ · builtins >=3.6 · tested on 3.9
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.