FileNotFoundError
builtins.FileNotFoundError
Stack trace
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' 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
The file path is misspelled or incorrect.
Verify and correct the file path string to match the exact location and filename on disk.
The file does not exist at the specified location.
Create the file before opening it in read mode or check for existence and handle the missing file case.
Relative path is used but the working directory is different than expected.
Use absolute file paths or ensure the working directory is set correctly before opening the file.
Code: broken vs fixed
with open('myfile.txt', 'r') as f: # This line raises FileNotFoundError if file missing
content = f.read()
print(content) 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}") 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.