Python FileNotFoundError: No such file or directory
1FileNotFoundError: overview
A FileNotFoundError means Python tried to open or access a file or folder path that does not exist, usually because the path is wrong relative to where the program is running.
Before this lesson: Python Exceptions: try, except, else and finally, Python File Handling
2FileNotFoundError: diagram
3FileNotFoundError: explained step by step
A FileNotFoundError means Python tried to open, read or list a path and nothing exists there. The file may truly be missing, but more often the path is slightly wrong: a different folder, a typo, or a folder that was never created.
What the message is telling you
The full text is [Errno 2] No such file or directory: 'scores.txt'. The quoted part is the exact path you gave Python, character for character. Errno is the operating system's error number: you may see 2 on your computer and a different number in the browser editor, because the browser uses a small built-in file system. The class name is what matters.
try:
with open("scores.txt") as f:
data = f.read()
except FileNotFoundError as err:
print("Class:", type(err).__name__)
print("Path Python tried:", err.filename)Reading is the default mode, so Python never creates a file for you when you open one with "r". The file handling lesson covers every mode.
How to read the traceback
Traceback (most recent call last):
File "report.py", line 3, in <module>
with open("data/scores.txt") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data/scores.txt'
- The last line gives the exact path that failed. Compare it with where the file really lives.
- The line above shows which
open()call used that path. - If the path is built from variables, print it just before the call to see what Python sees.
Cause 1: the path is relative to a different folder
A relative path such as data/scores.txt is measured from the working directory, the folder the program was started from, and not from the folder where your script file sits. Starting the same script from another folder changes the result. On your own machine, print the working directory to find out:
python -c "import os; print(os.getcwd())"
Build paths with pathlib so they stay correct, and check them with exists():
from pathlib import Path
Path("project/data").mkdir(parents=True, exist_ok=True)
Path("project/data/prices.txt").write_text("4.50\n")
print(Path("project/data/prices.txt").exists()) # correct path
print(Path("project/prices.txt").exists()) # forgot the data folderCause 2: a typo, wrong case or hidden extension
Scores.txt, score.txt and scores.txt.txt are three different names. On Linux, macOS servers and in this browser editor, upper and lower case count as different letters. Some Windows setups also hide known extensions, so a file you think is notes.txt is really notes.txt.txt. List the folder with os.listdir() and compare the real names.
Cause 3: the file was never created
Opening a file for reading before anything has written it fails. If the program should create the file the first time it runs, open with "a" (append, creates when missing) or catch the error and create a default.
Cause 4: the folder does not exist when you write
Even open("reports/out.txt", "w") raises this error when reports is missing. Mode "w" creates the file, never the folder. Create the folder first:
import os
os.makedirs("reports_demo", exist_ok=True)
with open("reports_demo/out.txt", "w") as f:
f.write("saved\n")
print(sorted(os.listdir("reports_demo")))Cause 5: separators and escape sequences in Windows paths
In a normal string, "C:\new\table.txt" contains a newline (\n) and a tab (\t), so the path is nonsense. Use forward slashes (they work on every system), a raw string r"C:\new\table.txt", or Path("C:/new/table.txt").
Fix: check first, or catch the error
Use Path.exists() or is_file() when a missing file is an expected situation. Use try and except when the file might disappear between the check and the read, or you want one place that handles the problem. Always catch FileNotFoundError specifically. Combine either with the with statement so files close properly.
from pathlib import Path
settings = Path("settings_demo.txt")
settings.unlink(missing_ok=True)
try:
theme = settings.read_text()
except FileNotFoundError:
theme = "light"
settings.write_text(theme)
print("Theme:", theme)
print("Saved:", settings.exists())Similar errors that look related
FileNotFoundError is a subclass of OSError, as are PermissionError (you are not allowed to open the path) and IsADirectoryError (you tried to open a folder as if it were a file). FileExistsError appears when mode "x" is used on a file that already exists. Reading data formats such as CSV files or JSON uses the same open(), so the same causes and fixes apply.
4FileNotFoundError: syntax
open("data/scores.txt") # relative to the working directory
Path("data/scores.txt").exists() # True/False, no error
Path("data").mkdir(parents=True, exist_ok=True) # create folders
open("log.txt", "a") # append mode creates the file
try:
text = path.read_text()
except FileNotFoundError:
text = "" # fallback
5FileNotFoundError: run the example
Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.
from pathlib import Path
Path("notes").mkdir(exist_ok=True)
path = Path("notes/todo.txt")
path.unlink(missing_ok=True)
try:
text = path.read_text()
except FileNotFoundError:
print("todo.txt is missing, creating it")
path.write_text("buy milk\n")
text = path.read_text()
print(text.strip())
print(path.exists())Expected outputtodo.txt is missing, creating it
buy milk
True
7FileNotFoundError: how the example works
Hover or tap a step to highlight its lines in the example above.
- Line 1
Pathfrompathlibrepresents a file path and has methods to read, write and check it. - Line 3Create the
notesfolder first.exist_ok=Truemeans it is fine if the folder is already there. - Line 4-5
pathpoints atnotes/todo.txt.unlink(missing_ok=True)deletes the file if it exists, so this demo starts the same way every run. - Line 7-8
read_text()opens the file for reading. Because the file does not exist, it raisesFileNotFoundError. - Line 9-11The
exceptblock runs instead of a crash: it reports the problem, writes a first version of the file and reads it back. - Line 13-14
strip()removes the trailing newline for printing, andexists()confirms the file now exists.
8FileNotFoundError: common mistakes
Running the script from a different folder
✗ Wrong
# scores.csv is next to report.py, but the program
# was started from the parent folder
with open("data/scores.csv") as f:
print(f.read())✓ Right
from pathlib import Path
path = Path("data/scores.csv")
print(path.exists())Relative paths start at the working directory, not at the script. Check that the full path, including every folder, matches where the file really is, or build an absolute path from the script's location with Path(__file__).parent.
Reading a file before anything has created it
✗ Wrong
with open("diary.txt") as f:
entries = f.read()✓ Right
try:
with open("diary.txt") as f:
entries = f.read()
except FileNotFoundError:
entries = ""
print(repr(entries))Mode "r" only reads existing files. Create the file first with "w" or "a", or catch the error and start with an empty diary.
A doubled extension
✗ Wrong
# the file is really named notes.txt.txt
with open("notes.txt") as f:
print(f.read())✓ Right
import os
print(os.listdir(".")) # compare these names with the path you typedSome systems hide known extensions, so notes.txt is displayed for a file actually called notes.txt.txt. List the folder with os.listdir() to see the real names and use exactly that.
Writing into a folder that does not exist
✗ Wrong
with open("reports/summary.txt", "w") as f:
f.write("Done")✓ Right
import os
os.makedirs("reports", exist_ok=True)
with open("reports/summary.txt", "w") as f:
f.write("Done")Mode "w" creates the file but never the folder. Create the folder first with os.makedirs(..., exist_ok=True) or Path.mkdir(parents=True, exist_ok=True).
Backslashes in a Windows path
✗ Wrong
with open("C:\new\table.txt") as f:
print(f.read())✓ Right
from pathlib import Path
path = Path("C:/new/table.txt")
print(path.name)In a normal string \n is a newline and \t is a tab, so the path Python receives is not the one you meant. Use a raw string, forward slashes or Path.
9FileNotFoundError: exercises
Write your answer, then press Check. The checks run in your browser.
1. Predict which files are found
Predict the output Easy ✓ CompletedRead the code and type exactly what it prints. Names are case-sensitive here. Then press Check to compare.
import os
os.makedirs("shelf", exist_ok=True)
with open("shelf/a.txt", "w") as f:
f.write("hi")
for name in ["a.txt", "A.txt", "a.txt.txt"]:
try:
with open("shelf/" + name) as f:
f.read()
print(name, "found")
except FileNotFoundError:
print(name, "missing")a.txt was created. A capital letter or an extra extension makes a different path.a.txt found
A.txt missing
a.txt.txt missing
2. Fix the missing export folder
Fix the bug Easy ✓ CompletedThis code saves two rows into exports/scores.csv and reads them back into saved, but it raises FileNotFoundError. Fix it so the file is written and saved equals "Asha,90\nBen,75". Keep the shutil.rmtree line, which just resets the demo.
import os
import shutil
shutil.rmtree("exports", ignore_errors=True) # start clean
rows = ["Asha,90", "Ben,75"]
with open("exports/scores.csv", "w") as f:
f.write("\n".join(rows))
with open("exports/scores.csv") as f:
saved = f.read()
print(saved)exports before opening the file.import os
import shutil
shutil.rmtree("exports", ignore_errors=True) # start clean
rows = ["Asha,90", "Ben,75"]
os.makedirs("exports", exist_ok=True)
with open("exports/scores.csv", "w") as f:
f.write("\n".join(rows))
with open("exports/scores.csv") as f:
saved = f.read()
print(saved)
2 more exercises → 6 more examples
Questions learners ask
My file is right there in the folder. Why does Python say it is not found?
Python looks relative to the working directory, which is the folder the program was started from, not necessarily the folder holding your script. Print os.getcwd() (or Path.cwd()) and compare it with the file's real location, then use a longer relative path or an absolute path. Also check for typos, upper/lower case and a hidden double extension such as notes.txt.txt.
Why does open(path, 'w') raise FileNotFoundError if it creates files?
Write mode creates the file but not the folders leading to it. If the folder in the path does not exist yet, Python reports No such file or directory. Create it first with os.makedirs(folder, exist_ok=True) or Path(folder).mkdir(parents=True, exist_ok=True).
Should I check os.path.exists() or use try/except FileNotFoundError?
Use exists() or is_file() when a missing file is a normal case and you want to branch clearly. Use try/except when you simply want to open the file and handle the failure, because the file could still disappear between the check and the open. Both are correct; catch FileNotFoundError specifically, not a bare except.
Further reading
10Next lesson
Up nextPython UnboundLocalErrorAn UnboundLocalError means a function used a local variable before it had a value, which happens because assigning to a…Related:
Python Exceptions: try, except, else and finallyPython File HandlingPython with StatementPython pathlib
← Python ZeroDivisionError: Division by Zero · All Errors and Exceptions lessons · Practise in the IDE