FileNotFoundError: No such file or directory
Python couldn't find the file to open. Its name is looked up next to your program, so the file has to be there with exactly that name.
Your error
Check these first
- Is the file here? In this editor, a file your program reads has to be in the project: add it as a new tab.
- The exact name.
data.txt,Data.txtanddata.csvare three different files. - No paths from your computer.
C:/Users/...is on your computer, not here: use just the file's name.
Causes and fixes
1 The file isn't in the project
Add the file with the + button beside the file tabs, named exactly as in open(), or have the program write it first, as below.
with open("data.txt") as f:
print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
with open("data.txt", "w") as f:
f.write("Hello from the file")
with open("data.txt") as f:
print(f.read())
Hello from the file
2 A typo or the wrong extension
The name in open() has to match the file exactly, extension included.
with open("notes.csv", "w") as f:
f.write("a,b")
with open("notes.txt") as f:
print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'
with open("notes.csv", "w") as f:
f.write("a,b")
with open("notes.csv") as f:
print(f.read())
a,b
3 A path from your computer
An online editor can't see the files on your computer. Add the file to the project, then open it by its name alone.
with open("C:/Users/ada/data.txt") as f:
print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/ada/data.txt'
with open("data.txt", "w") as f:
f.write("Hello from the file")
with open("data.txt") as f:
print(f.read())
Hello from the file
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Reading and Writing Files
- Other errors: AttributeError, IndentationError, IndexError, KeyError, ModuleNotFoundError, NameError, RecursionError, SyntaxError, TypeError, UnboundLocalError, ValueError, ZeroDivisionError