FileNotFoundError: [Errno 2] No such file or directory
FileNotFoundError: [Errno 2] No such file or directory
DodaTech
3 min read
FileNotFoundError: [Errno 2] No such file or directory appears when you try to open, read, or write to a file path that doesn’t exist. This is one of the most common I/O errors in Python.
What It Means
The operating system reported that the path you gave doesn’t point to an existing file or directory. Python can’t create or access the file at that location automatically — you need to provide a valid path.
Why It Happens
- The file doesn’t exist (typo in filename, wrong directory)
- Using relative paths when the current working directory isn’t what you think
- The file is in a different directory than expected
- The filename extension is wrong or missing
- The program doesn’t have permission to see the file (different issue, same error on some OS)
- Symbolic link is broken
How to Fix It
Step 1: Use an absolute path
# BAD — relative path depends on where the script runs
with open("data.txt") as f:
content = f.read()
# GOOD — use an absolute path
with open("/home/user/project/data.txt") as f:
content = f.read()
# Or build the path relative to the script's location
from pathlib import Path
base = Path(__file__).parent
path = base / "data.txt"
with open(path) as f:
content = f.read()Step 2: Check your current working directory
import os
# Print where Python thinks it is
print(os.getcwd())Then either change to the correct directory or adjust the path.
Step 3: Verify the file exists before opening
import os
from pathlib import Path
path = "data.txt"
# Option A
if os.path.exists(path):
with open(path) as f:
print(f.read())
else:
print(f"File '{path}' not found")
# Option B (modern)
p = Path(path)
if p.is_file():
print(p.read_text())
else:
print(f"File '{path}' not found")Step 4: List files in the directory to find the correct name
import os
directory = "."
for f in os.listdir(directory):
print(f)Step 5: Create parent directories if writing a file
from pathlib import Path
path = Path("output/subdir/results.txt")
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("Hello, file!")Step 6: Use try/except for robust file operations
try:
with open("data.txt") as f:
content = f.read()
except FileNotFoundError:
print("File not found. Creating with default content...")
with open("data.txt", "w") as f:
f.write("default") Previous
HTTP 405 Method Not Allowed — What It Means & How to Debug
Next
java.lang.IllegalArgumentException
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro