How to Fix Python FileNotFoundError
In this tutorial, you'll learn about How to Fix Python FileNotFoundError. We cover key concepts, practical examples, and best practices.
The Problem
You run a Python script that reads a file and get:
Traceback (most recent call last):
File "script.py", line 3, in <module>
with open("data.txt", "r") as f:
FileNotFoundError: [Errno 2] No such file or directory: 'data.txt'
Python cannot find the file at the specified path. The file may not exist, the path may be relative to the wrong directory, or the filename has a typo.
Quick Fix
Step 1: Check the current working directory
python3 -c "import os; print(os.getcwd())"
Your script looks for data.txt in this directory, not where the script is located.
Step 2: Use an absolute path
Change the script to use an absolute path:
with open("/home/user/project/data.txt", "r") as f:
print(f.read())
Or build the path relative to the script location:
import os
script_dir = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(script_dir, "data.txt")
with open(file_path, "r") as f:
print(f.read())
Step 3: Verify the file exists
ls -la data.txt
python3 -c "print(open('data.txt').read())"
Expected output:
-rw-r--r-- 1 user user 1024 Mar 15 10:30 data.txt
file contents here
Step 4: Check for typos
# List files in the directory
ls -la
# Expected: data.txt (not date.txt or data.dat)
Alternative Solutions
Use pathlib for cross-platform path handling:
from pathlib import Path
file_path = Path(__file__).parent / "data.txt"
with open(file_path) as f:
print(f.read())
Verify Your Python Environment
python3 --version
# Python 3.10.12
pip list | grep requests
# requests 2.31.0
Check your Python version and installed packages before debugging. Many errors are caused by version mismatches between development and production environments. Using a virtual environment with pinned dependencies prevents these surprises.
Additional Troubleshooting
# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"
If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.
Prevention
- Use
os.path.abspath(__file__)to locate files relative to the script. - Always check file existence with
os.path.exists(path)before opening. - Use
pathlib.Pathfor modern, cross-platform file paths. - Print the absolute path when debugging:
print("Looking for:", os.path.abspath(filename)).
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro