File or directory not found
A subclass of `OSError`, this exception is raised when you try to access a file or directory that does not exist. This is one of the most common I/O errors developers encounter.
- 1A typo in the file or directory path.
- 2The file exists, but in a different directory from where the script is being executed (a common relative path issue).
- 3The file was deleted, moved, or renamed before the program tried to access it.
This error is triggered when `open()` is used to read a file that does not exist at the specified path.
with open("this_file_does_not_exist.txt", "r") as f:
content = f.read()
expected output
Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'this_file_does_not_exist.txt'
Fix 1
Use an absolute path or verify the relative path
WHEN You are not sure about the script's current working directory.
# Use an absolute path
# path = "C:/Users/test/my_file.txt" # Windows
path = "/home/user/my_file.txt" # Linux/macOS
try:
with open(path, "r") as f:
print(f.read())
except FileNotFoundError:
print(f"File not found at: {path}")
Why this works
An absolute path is unambiguous and does not depend on the current working directory, making it a more robust way to locate files.
Fix 2
Check if the file exists before opening
WHEN The file is optional and the program can continue without it.
import os
path = "optional_config.txt"
if os.path.exists(path):
with open(path, "r") as f:
# process file
pass
else:
print("Optional config not found, using defaults.")
Why this works
`os.path.exists()` safely checks for the existence of a file or directory without raising an error, allowing your program to decide how to proceed.
with open("missing.txt") as f:
content = f.read() # FileNotFoundErrortry:
with open(path) as f:
data = f.read()
except FileNotFoundError:
data = Nonefrom pathlib import Path
p = Path("config.txt")
data = p.read_text() if p.exists() else "{}"✕ Creating the file if it doesn't exist when you expected it to be there
If your program's logic depends on a file being present (e.g., a config file), creating an empty one can mask the real problem and lead to other errors downstream.
cpython/Objects/exceptions.c
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev