Fix: FileNotFoundError: No such file or directory
Exact message
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'
Quick answer
FileNotFoundError means Python's open() could not find the file at the path you specified. The most common cause is a relative path that resolves against the current working directory, which is rarely the script's folder.
Why this error happens
open('data.csv') resolves against os.getcwd(), not the location of the script. So a file next to your script still fails if you run the script from another directory. Absolute paths or pathlib.Path(__file__).parent both avoid this trap.
Example: Wrong vs Right
Wrong
with open('data.csv') as f:
print(f.read())
# FileNotFoundError: [Errno 2] ... 'data.csv'Right
from pathlib import Path
# Resolve relative to the script, not the working directory
here = Path(__file__).parent
with open(here / 'data.csv') as f:
print(f.read())How to fix it (step by step)
- Print os.getcwd() to see the actual working directory
- Print os.listdir() to confirm the file's location
- Use pathlib.Path(__file__).parent to anchor paths to the script file
- Avoid hardcoded paths; use environment variables or config files for portability
Frequently asked questions
Why does it work in terminal but not in an IDE?
The terminal and the IDE set different working directories. The file path is relative, so it resolves differently. Use absolute paths or pathlib to fix.
How do I fix this in Docker?
Copy the data file into the image with COPY in the Dockerfile. The container's working directory has no access to your host filesystem.
Should I use os.path or pathlib?
pathlib. It is more readable, cross-platform, and available since Python 3.4. The / operator builds paths safely.
Related Python errors
Need a fix for a different error?
Use the free to paste any traceback and get an AI-suggested fix in seconds.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.