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.
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'How to fix it
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.
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 = "{}"Related errors
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