Fix FileNotFoundError in Python
Error Reference
FileNotFoundError: [Errno 2] No such file or directory
Python can't find the file at the path you gave it. Here's how to track down why.
Checklist
- Typos? Check the filename and extension —
data.csvis notData.CSVon Linux. - Right directory? Print
os.getcwd()— relative paths resolve against the working directory, not the script's location. - File exists yet? Reading a file that hasn't been created raises this; writing with mode
'w'or'a'creates it. - Missing parent folder?
open('out/result.txt', 'w')fails ifout/doesn't exist.
Relative paths
The most common cause: the script works when run from one folder and fails from another.
import os
print(os.getcwd()) # where relative paths actually resolve
# FileNotFoundError when run from the wrong directory
data = open('data.csv')
Anchor paths to the script's own location instead:
from pathlib import Path
HERE = Path(__file__).parent
data = (HERE / 'data.csv').read_text()
Check before opening
from pathlib import Path
path = Path('data.csv')
if path.exists():
content = path.read_text()
else:
print(f'{path.resolve()} does not exist')
Or handle the exception where the file is genuinely optional:
try:
content = Path('config.toml').read_text()
except FileNotFoundError:
content = '' # fall back to defaults
Creating missing directories
from pathlib import Path
out = Path('reports/2026')
out.mkdir(parents=True, exist_ok=True)
(out / 'summary.txt').write_text('done')
Frequently Asked Questions
What does "[Errno 2] No such file or directory" mean?
Errno 2 is the operating system error code (ENOENT) for a path that does not exist. Python wraps it in FileNotFoundError, a subclass of OSError. The message includes the path Python looked for — read it carefully; it is usually not the path you intended.
Why does my script work in the IDE but fail in the terminal?
IDEs often set the working directory to the project root, while a terminal uses whatever directory you are standing in. Relative paths then resolve differently. Build paths from __file__ so they work in both.
from pathlib import Path
DATA = Path(__file__).parent / 'data.csv'
How do I create the file if it does not exist?
Open it in write ('w') or append ('a') mode — both create the file. Mode 'x' creates it but fails if it already exists, which is useful for avoiding accidental overwrites.
with open('log.txt', 'a') as f:
f.write('first line\n')