How to Fix FileNotFoundError: [Errno 2] in Python
In this tutorial, you'll learn about How to Fix FileNotFoundError: [Errno 2] in Python. We cover key concepts, practical examples, and best practices.
Python raises FileNotFoundError: [Errno 2] No such file or directory when you try to open a file that does not exist at the specified path.
The Wrong Way
with open("data.csv", "r") as f:
content = f.read()
This produces:
Traceback (most recent call last):
File "script.py", line 1, in <module>
with open("data.csv", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'
The Right Way
Check if the file exists before opening it:
import os
filename = "data.csv"
if os.path.exists(filename):
with open(filename, "r") as f:
content = f.read()
else:
print(f"File {filename} not found")
Output:
File data.csv not found
Step-by-Step Fix
1. Verify the current working directory
import os
print("Current directory:", os.getcwd())
print("Files:", os.listdir('.'))
2. Use absolute paths
import os
filepath = os.path.abspath("data.csv")
print("Looking for:", filepath)
if os.path.exists(filepath):
with open(filepath, "r") as f:
content = f.read()
3. Use pathlib for cleaner paths
from pathlib import Path
filepath = Path("data/data.csv")
if filepath.exists():
content = filepath.read_text()
else:
print(f"File not found: {filepath.resolve()}")
4. Create the file if needed
from pathlib import Path
filepath = Path("output.txt")
filepath.write_text("Default content")
print("File created")
Prevention Tips
- Use
os.path.exists()orPath.exists()before opening files. - Use absolute paths for production code.
- Use
pathlib.Pathfor cross-platform path handling. - Create required directories with
Path.mkdir(parents=True, exist_ok=True). - Use try-except to handle missing files gracefully in user-facing applications.
Common Mistakes with filenotfound
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro