How to Resolve Python "FileNotFoundError: [Errno 2] No such file or directory"
The FileNotFoundError: [Errno 2] No such file or directory is one of the most common exceptions encountered by Python developers when working with files. It signifies that Python attempted to access a file using a specified path, but no file or directory was found at that exact location.
This guide explains the common causes of this error and provides step-by-step solutions to correctly locate and open your files.
Understanding the Error: The File Path Problem
When you use functions like open(), Python interprets the filename you provide as a path. This path tells Python where to look for the file. The FileNotFoundError simply means Python followed the path instructions but didn't find anything at the specified destination.
Common Causes
- File Doesn't Exist: The file truly isn't present on the filesystem.
- Incorrect Path: The path provided leads to the wrong location.
- Wrong Relative Path: The file isn't located correctly relative to where the script is being run.
- Wrong Absolute Path: The full path from the root directory is incorrect.
- Spelling Mistakes: Typos in the filename or directory names within the path.
- Missing File Extension: Forgetting to include
.txt,.csv,.json, etc., in the filename (Windows often hides extensions by default, making this easy to miss). - Case Sensitivity: On case-sensitive systems (Linux, macOS),
myfile.txtis different fromMyFile.txt. - Permissions: The script might lack the necessary operating system permissions to access the file's location.
Understanding Path Types: Relative vs. Absolute
Relative Paths
A relative path specifies the file's location in relation to the current working directory (CWD). The CWD is typically the directory from where you executed the Python script.
'my_data.csv': Looks for the file in the CWD.'data/my_data.csv': Looks for a folder nameddatawithin the CWD, and then formy_data.csvinside that folder.'../backup/my_data.csv': Goes up one directory level from the CWD, then looks for abackupfolder, and then for the file inside it.
Absolute Paths
An absolute path specifies the file's complete location starting from the root directory of the filesystem. They are unambiguous, regardless of the CWD.
- Windows:
C:\Users\Alice\Documents\project\my_data.csv - macOS/Linux:
/Users/alice/Documents/project/my_data.csvor/home/bob/data/my_data.csv
Finding Your Current Working Directory (os.getcwd)
If you're unsure what the CWD is when using relative paths, you can easily find it:
import os
cwd = os.getcwd()
print(f"The current working directory is: {cwd}")
# Example Output (Linux/macOS): /home/user/my_python_project
# Example Output (Windows): C:\Users\User\Documents\MyPythonProject
Knowing the CWD helps you construct the correct relative path.
Solution 1: Using Correct Relative Paths
Placing the File in the Same Directory
The simplest case: If you use just the filename (e.g., 'config.txt'), make sure config.txt is located in the exact same folder as the Python script you are running.
Accessing Files in Subdirectories
If the file is inside a folder relative to your script, include the folder name in the path.
# Assumes:
# my_project/
# |- main.py
# |- input_data/
# |- data.csv
# Correct relative path from main.py
file_path = 'input_data/data.csv'
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
print(f"Successfully read {file_path}")
except FileNotFoundError:
print(f"Error: Could not find file at relative path '{file_path}'")
Accessing Files in Parent Directories (../)
Use ../ to navigate up one directory level. Use ../../ to go up two levels, etc.
# Assumes:
# project_root/
# |- config.txt
# |- src/
# |- main.py
# Correct relative path from main.py to config.txt
file_path = '../config.txt'
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
print(f"Successfully read {file_path}")
except FileNotFoundError:
print(f"Error: Could not find file at relative path '{file_path}'")
Best Practice: Using os.path.join
To construct paths in a way that works correctly across different operating systems (handling / vs \ automatically), use os.path.join().
import os
# Assumes script is in 'my_project/src/'
# Wants to access 'my_project/data/results.json'
script_dir = os.path.dirname(__file__) # Gets directory of the current script
project_root = os.path.abspath(os.path.join(script_dir, '..')) # Go up one level
file_path = os.path.join(project_root, 'data', 'results.json')
print(f"Constructed path: {file_path}")
try:
with open(file_path, 'r', encoding='utf-8') as f:
print(f"Successfully opened {file_path}")
# ... read file ...
except FileNotFoundError:
print(f"Error: File not found at constructed path '{file_path}'")
Solution 2: Using Absolute Paths
Using the full, unambiguous path avoids issues related to the CWD.