FileNotFoundError: What It Means and How to Fix It
Error reference
FileNotFoundError
Language
Severity
MediumWhen it happens
A FileNotFoundError is raised in Python when the interpreter tries to open or access a file that does not exist at the given path.
Potential fixes
Use pathlib.Path and check .exists() before opening. Print or log the resolved absolute path with Path.resolve() to confirm you are looking in the right place. When bundling scripts, use __file__ to build paths relative to the script's own location rather than the current working directory.
Related errors
Deep dive
A FileNotFoundError is raised in Python when the interpreter tries to open or access a file that does not exist at the given path. It is a subclass of OSError and is the most common file-system error you will encounter.
Why it happens
- •The file path is relative and the working directory is not what you expect when the script runs.
- •A typo or incorrect path separator in the file path string.
- •The file was deleted, moved, or never created before the script ran.
- •The path points to a directory, not a file.
Potential fixes
Use pathlib.Path and check .exists() before opening. Print or log the resolved absolute path with Path.resolve() to confirm you are looking in the right place. When bundling scripts, use __file__ to build paths relative to the script's own location rather than the current working directory.
Examples
Code that triggers the error
with open("config.json") as f:
data = f.read()Error output
Traceback (most recent call last):
File "app.py", line 1, in <module>
with open("config.json") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'config.json'Fixed code
from pathlib import Path
config_path = Path("config.json")
if config_path.exists():
with config_path.open() as f:
data = f.read()
else:
print("Config file not found, using defaults")
data = "{}"Practice in English
How would you explain a FileNotFoundError to a fellow dev? Choose the right phrase:
"I hit an error...
Ready to practice your English at work?
Lingua-e has interactive exercises built around real developer conversations: standups, code reviews, retrospectives, and more. Practice until it comes naturally.
Try Lingua-e for free