FileNotFoundError: [Errno 2] No such file or directory
Error message
[Errno 2] No such file or directory: 'missing.txt'
Quick summary
You tried to open, read, or access a file that doesn't exist at the specified path.
Why this happens
Typo in the file name or path
The file hasn't been created yet
Wrong working directory — relative path doesn't resolve
Missing file extension
Minimal example
with open("missing.txt", "r") as f:
content = f.read() # FileNotFoundErrorimport os
if os.path.exists("data.txt"):
with open("data.txt", "r") as f:
content = f.read()
else:
print("File not found")
content = ""Check if the file exists with os.path.exists() before opening, or wrap in try/except FileNotFoundError.
How to diagnose
Check the file path spelling and case (case-sensitive on Unix)
Verify the file exists with os.path.exists()
Print the current working directory with os.getcwd()
How to fix
Correct the file path or name
Create the file before opening it
Use an absolute path instead of a relative path
Use try/except FileNotFoundError to handle missing files
How to prevent
Check os.path.exists() before opening
Use context managers (with open(...)) for file access
Validate file paths from user input
Related Resources
Related Lessons
- File Handling
File errors.
Related Practice
- Fill: File Mode
File operations.