FileNotFoundError
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'
Traceback
Traceback (most recent call last):
File "main.py", line 2, in <module>
content = f.read()
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'What causes this error
The specified file or directory path does not exist on the filesystem. Common causes include incorrect relative paths, typos in file names, files that have been moved or deleted, and running scripts from the wrong directory.
How to fix it
Verify the path with `os.path.exists()` or `Path.exists()` before accessing. Use absolute paths or `pathlib` for reliable path resolution. Print the current working directory with `os.getcwd()` to debug relative path issues.
Code that causes this error
with open("data.csv") as f:
content = f.read()Fixed code
from pathlib import Path
file_path = Path("data.csv")
if file_path.exists():
content = file_path.read_text()
else:
print(f"File not found: {file_path.resolve()}")About FileNotFoundError
A FileNotFoundError is raised when attempting to open or access a file or directory that does not exist. This is a subclass of OSError and one of the most common errors in data processing and file I/O operations. The error typically occurs with `open()`, `os.stat()`, `pathlib.Path` operations, and similar filesystem calls.
The most frequent causes are incorrect file paths (especially relative paths that depend on the current working directory), typos in filenames, files that have been moved or deleted, and running a script from a different directory than expected. The error message includes the filename, making it straightforward to debug. Using `pathlib.Path` with its `.exists()` method, `os.path.isfile()`, or try/except blocks are all valid defensive strategies.
When building paths, prefer `pathlib.Path` or `os.path.join()` over string concatenation for cross-platform compatibility.
Common scenarios
Opening files with incorrect or relative paths
Reading files that have been moved, renamed, or deleted
Writing to directories instead of files or vice versa
Working with file streams that have been closed prematurely