Python FileNotFoundError: No such file or directory
A plain-words explanation of this Python message: what it means, the usual causes, and the steps that fix it.
The messageFileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
Make the error yourself
Run with Python 3.14.10. This is the smallest example we could find that shows it.
Python program (main.py)
with open("data.txt") as f:
print(f.read())Output (the real message)
Traceback (most recent call last):
File "main.py", line 1, in <module>
with open("data.txt") as f:
~~~~^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'Why it happens
Python looked for the file name in the message and it is not there. A relative name like data.txt is searched in the current working directory, which is the folder the program was started from, not necessarily the folder that holds your script. Other causes: a typo, a wrong extension (a file shown as data in Windows may really be data.txt), a file that has not been created yet, or a path with \ that Python reads as an escape code.
How to fix it
- Print the folder Python is using:
import os; print(os.getcwd()). - Compare it with where the file is. Either move the file there, start the program from the right folder, or give the full path.
- To find the file next to your script, use
Path(__file__).parent / "data.txt". - In Windows paths, write
r"C:\Users\me\data.txt"(with the r in front) or use forward slashes. - Show file extensions in your file manager so you see the real names.
The corrected version
Python program (main.py)
from pathlib import Path
path = Path("data.txt")
path.write_text("hello\n", encoding="utf-8")
if path.exists():
print(path.read_text(encoding="utf-8").strip())Output (the corrected version)
helloHow to avoid it
Build paths with pathlib.Path, and check path.exists() when the file may be missing, with a clear message.
Questions
Why does my script work in the editor but not when I double-click it?
The working directory is different. Use a path built from __file__.
This is an independent guide. It is not connected with Python, Microsoft, Google, GitHub or the Git project. Product names belong to their owners. Examples were run on 13 November 2026 in a practice folder or a blank workbook; your version may word a message slightly differently.