FileNotFoundError: Errno 2 No such file or directory (Fix)
FileNotFoundError: [Errno 2] No such file or directory means Python could not find the file or folder path you gave it.
This error is very common when working with open(), os, or pathlib. In most cases, the problem is one of these:
- The file name is wrong
- The file is in a different folder
- The path is relative, but Python is running from a different working directory
- A folder in the path does not exist
If you want a fast way to check the path before opening the file, use this:
from pathlib import Path
file_path = Path("data.txt")
if file_path.exists():
with open(file_path, "r", encoding="utf-8") as file:
content = file.read()
print(content)
else:
print(f"File not found: {file_path.resolve()}")
Use this when you are not sure whether the file exists. It checks the path before opening it and shows the full path for debugging.
What this error means
This error means Python tried to access a path, but that path was not found.
That can happen when:
- The file does not exist
- The folder does not exist
- The path points to the wrong location
- You expected Python to run from one folder, but it is actually running from another
You will often see this error with:
open()os.listdir()os.remove()pathlib.Path.read_text()pathlib.Path.open()
If you are new to file handling, it helps to first understand the Python open() function and working with file paths in Python.
When this error usually happens
FileNotFoundError usually appears in one of these situations:
- You try to open a file that does not exist
- You use a relative path like
"data.txt", but Python is running from a different folder - You misspell the file name or extension
- You try to access a folder path that does not exist yet
- You build the path incorrectly with slashes or manual string concatenation
Common examples:
- Writing
report.txtwhen the real file isreports.txt - Using
.txtwhen the file is really.csv - Trying to write to
output/result.txtwhen theoutputfolder does not exist - Using
folder" + "/" + filenameand accidentally creating the wrong path
Example that causes the error
Here is a minimal example:
with open("missing.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
If missing.txt is not in the current working directory, Python raises:
Traceback (most recent call last):
File "example.py", line 1, in <module>
with open("missing.txt", "r", encoding="utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
The important part is the last line:
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
That tells you exactly which path Python failed to find.
How to fix it
Here are the fastest ways to fix this error.
1. Check that the file really exists
Make sure the file is actually there.
For example, if your code uses:
open("data.txt", "r")
confirm that data.txt exists in the folder where Python is running.
2. Check the file name, extension, and capitalization
Small differences matter.
Check for mistakes like:
data.txtvsData.txtreport.csvvsreport.txtimage.PNGvsimage.png
On some systems, capitalization matters.
3. Print the current working directory
A relative path like "data.txt" depends on the current working directory, not always the script location.
import os
print(os.getcwd())
If this folder is not where your file is, Python will not find it.
If you are using the os module, this is also a good time to review the Python os module overview.
4. Use the correct absolute or relative path
If the file is in a subfolder, include that folder:
with open("files/data.txt", "r", encoding="utf-8") as file:
print(file.read())
An absolute path also works:
with open("/full/path/to/data.txt", "r", encoding="utf-8") as file:
print(file.read())
5. Build paths safely
Avoid building paths by hand when possible.
Using pathlib:
from pathlib import Path
file_path = Path("files") / "data.txt"
with open(file_path, "r", encoding="utf-8") as file:
print(file.read())
Using os.path.join():
import os
file_path = os.path.join("files", "data.txt")
with open(file_path, "r", encoding="utf-8") as file:
print(file.read())
If you want a method-by-method explanation, see os.path.join() explained.
6. Create the folder first when writing
If you write to a file inside a missing folder, Python cannot create the file until the folder exists.
This will fail if output does not exist:
with open("output/result.txt", "w", encoding="utf-8") as file:
file.write("Hello")
Fix it like this:
from pathlib import Path
output_dir = Path("output")
output_dir.mkdir(exist_ok=True)
file_path = output_dir / "result.txt"
with open(file_path, "w", encoding="utf-8") as file:
file.write("Hello")
Debugging steps to try
When you are not sure what is wrong, do these checks in order.
Print the exact path your code is using
from pathlib import Path
path = Path("data.txt")
print(path)
print(path.resolve())
This shows both the path you wrote and the full resolved path.
Print the current working directory
import os
print(os.getcwd())
Check whether the file exists
from pathlib import Path
print(Path("data.txt").exists())
You can also use os.path.exists():
import os
print(os.path.exists("data.txt"))
If you want more detail, see os.path.exists() explained.
If writing a file, check the parent folder
from pathlib import Path
file_path = Path("output/result.txt")
print(file_path.parent.exists())
If this prints False, create the folder before writing.
Avoid guessing where Python is running from
Do not assume Python runs from the same folder as your script. Check it directly with os.getcwd().
Relative path vs absolute path
This causes a lot of confusion for beginners.
Relative path
A relative path depends on the current working directory.
Example:
open("data.txt", "r")
This means:
- Look for
data.txt - In the folder Python is currently running from
Absolute path
An absolute path gives the full location of the file.
Example:
open("/home/user/project/data.txt", "r")
This does not depend on the current working directory.
Important beginner mistake
Many beginners think file paths are relative to the script file.
Often, they are relative to where the program was started instead.
If your file is next to your script, you can build the path from __file__:
from pathlib import Path
script_folder = Path(__file__).parent
file_path = script_folder / "data.txt"
with open(file_path, "r", encoding="utf-8") as file:
print(file.read())
This is one of the safest ways to access files stored beside your script.
How to prevent this error
You cannot avoid every missing-file case, but you can make your code much safer.
Use pathlib
pathlib makes paths easier to read and harder to build incorrectly.
from pathlib import Path
file_path = Path("data") / "report.txt"
print(file_path.exists())
Check file existence before reading
from pathlib import Path
file_path = Path("data.txt")
if file_path.exists():
print(file_path.read_text(encoding="utf-8"))
else:
print("File not found")
Use __file__ when the file is next to your script
from pathlib import Path
base_dir = Path(__file__).parent
file_path = base_dir / "config.json"
print(file_path)
Create missing folders before writing
from pathlib import Path
folder = Path("logs")
folder.mkdir(exist_ok=True)
log_file = folder / "app.log"
log_file.write_text("Started\n", encoding="utf-8")
Common causes
Here are the most common reasons this error happens:
- Wrong file name
- Wrong file extension such as
.txtvs.csv - File is in a different folder
- Current working directory is not the script folder
- Missing parent directory when writing a file
- Incorrect path separators or manually joined path strings
- Capitalization mismatch on case-sensitive systems
Useful debugging commands
These short commands can help you find the problem quickly:
import os
print(os.getcwd())
from pathlib import Path
print(Path("data.txt").resolve())
from pathlib import Path
print(Path("data.txt").exists())
import os
print(os.path.exists("data.txt"))
from pathlib import Path
print(Path("output").exists())
FAQ
Why do I get FileNotFoundError even though the file is in my project folder?
Your program may be running from a different working directory. Check os.getcwd() and compare it to the real file location.
Does open() create a file if it does not exist?
It depends on the mode:
"r"raisesFileNotFoundError"w"creates the file if needed- But the parent folder must already exist
What is the difference between FileNotFoundError and PermissionError?
FileNotFoundError means Python cannot find the path.
PermissionError means the path exists, but Python is not allowed to access it. See PermissionError: Errno 13 Permission denied (Fix).
Should I use try-except for this error?
Yes, if the file may genuinely be missing.
For example:
try:
with open("data.txt", "r", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("The file was not found.")
But do not use try-except as a substitute for checking your path logic. You should still find out why the path is wrong.
See also
- How to read a file in Python
- Working with file paths in Python
- Python
open()function explained - Python
osmodule overview os.path.exists()function explainedos.path.join()function explained- PermissionError: Errno 13 Permission denied (Fix)
- IsADirectoryError: Errno 21 Is a directory (Fix)
- FileNotFoundError in Python: causes and fixes