FileNotFoundError: [Errno 2] No such file or directory
What it means
Python could not find a file at the path you gave. A name without folders, like 'data.txt', is looked up only in the current working folder. The file may not exist yet, its name may differ slightly, or a folder in the path may be missing.
1. Reading a file that has not been created yet
This raises the error
Traceback (most recent call last): File "<exec>", line 1, in <module> FileNotFoundError: [Errno 44] No such file or directory: 'data.txt'
The fix
first line
Opening with 'r', the default, only reads files that already exist. Mode 'w' creates the file (or empties it), and 'a' creates it or adds to the end.
2. Not checking that the file exists
This raises the error
Traceback (most recent call last): File "<exec>", line 1, in <module> FileNotFoundError: [Errno 44] No such file or directory: 'settings.txt'
The fix
Theme: dark
os.path.exists() lets the program fall back to a default when the file is missing. Catching FileNotFoundError with try / except does the same job.
3. Writing into a folder that does not exist
This raises the error
Traceback (most recent call last): File "<exec>", line 1, in <module> FileNotFoundError: [Errno 44] No such file or directory: 'reports/summary.txt'
The fix
Saved: True
Mode 'w' creates a missing file but never a missing folder. os.makedirs(..., exist_ok=True) creates the folders, and does nothing if they are already there.
When you see this error, check
- Print
os.getcwd()andos.listdir()to see which folder Python is in and what is there. - Check the exact file name, including the extension:
data.txtanddata.txt.txtare different files. - In the pythoncompiler.io editor, upload a data file from the Files panel first. Your code can then open it by its name.
- On Windows, use forward slashes in paths, or a raw string like
r'C:\files\data.txt'.
Related errors
All Python errors · How to read a traceback · Step through your code