FileNotFoundError: [Errno 2] No such file or directory in Python
This error occurs when opening a file that does not exist at the resolved path. Use pathlib.Path with absolute paths or verify existence with path.exists().
Root Cause Analysis
This error occurs when Python tries to open or read a file at a specified system path, but no file or directory exists at that location in the operating system's filesystem.
Cause 1: Working Directory Mismatches with Relative Paths
Relative paths (e.g. 'data/config.json') are resolved relative to the current working directory (os.getcwd()), NOT the directory containing the Python script. If a script is launched from a terminal in a parent directory, relative lookups point to the wrong location.
Cause 2: Typographical Errors and Case Sensitivity in File Names
On Linux, macOS (APFS case-sensitive), and Docker containers, filenames are case-sensitive and whitespace-sensitive. Referencing 'Config.json' when the file is named 'config.json' raises FileNotFoundError.
Cause 3: Cross-Platform Path Separator Issues
Hardcoding Windows backslashes ('data\config.json') causes syntax escape issues or fails entirely on Linux/macOS environments. Using modern pathlib.Path eliminates separator incompatibilities.
Cause 4: Opening Missing Target Files in Read Mode
Calling open('file.txt', 'r') on a file that has not yet been generated raises FileNotFoundError: [Errno 2] No such file or directory.
Reproduction Code (MCVE)
target_file = 'non_existent_config_file.json'
with open(target_file, 'r') as f:
data = f.read()
Solution 1: Resolve File Paths Relative to the Script File via pathlib
Use Path(__file__).parent to construct absolute paths anchored to the script location, guaranteeing correct resolution regardless of where the terminal executes.
from pathlib import Path
# Anchor path to the script's directory
base_dir = Path(__file__).parent if '__file__' in globals() else Path.cwd()
config_path = base_dir / 'config_sample.txt'
# Ensure file exists or write fallback content
if not config_path.exists():
config_path.write_text('{"status": "initialized"}', encoding='utf-8')
content = config_path.read_text(encoding='utf-8')
print(f'Config loaded: {content}')
Solution 2: Defensive File Reading with try/except FileNotFoundError
Wrap file opening operations in structured exception handling to provide informative fallbacks or custom error messages.
from pathlib import Path
target_file = Path('runtime_metrics.json')
try:
with open(target_file, 'r', encoding='utf-8') as f:
data = f.read()
except FileNotFoundError:
print(f'Notice: {target_file} not found. Operating with default metrics.')
data = '{}'
print(f'Metrics data: {data}')
Common Mistakes & Edge Cases
1. Contrasting FileNotFoundError vs PermissionError
FileNotFoundError: The file path does not exist in the filesystem.PermissionError: The file exists, but the executing user account lacks read/write permissions or the file is locked by another process.
2. Creating Parent Directories Before Writing
Attempting to write to 'nested/folder/output.txt' when 'nested/folder' does not exist raises FileNotFoundError. Always call Path('nested/folder').mkdir(parents=True, exist_ok=True) before creating files.
3. Windows Path Escaping Pitfalls
Writing string paths like 'C:\test\new' can interpret \t as a tab and \n as a newline. Always use raw strings r'C:\test\new' or forward slashes Path('C:/test/new').