Python error explained
FileNotFoundError: what it means and how to fix it
The file you tried to open is not where Python looked.
The message
FileNotFoundError: [Errno 2] No such file or directory: 'scores.txt'
What it means
open() in read mode needs the file to exist. Python looks relative to the folder the program is running in, so a file that is somewhere else, or spelt differently, is not found. Opening in write mode ("w") creates the file instead.
Common causes
- The file name or extension is spelt differently
- The file is in another folder
- Reading a file before your program has written it
Example that raises it
with open("scores.txt") as f:
print(f.read())
The fix
try:
with open("scores.txt") as f:
print(f.read())
except FileNotFoundError:
print("No scores yet")
Tip: Catch FileNotFoundError when a missing file is a normal situation, such as the first time a program runs.
Fix the broken version yourself in the editor on this page. It runs real Python in your browser.