FileNotFoundError: [Errno 2] No such file or directory is raised when you try to open a file (with open() or similar) and the path does not exist or is not accessible. Python resolves relative paths from the process’s current working directory, not from the folder where your script lives. This guide explains common causes and how to fix them.

What this error means

When you call open(path), the OS looks for the file at path. If path is relative (e.g. 'data.txt'), it is resolved relative to the current working directory (what os.getcwd() returns). If the file is elsewhere—or the path has a typo or wrong extension—the OS reports “no such file or directory” and Python raises FileNotFoundError.

Common causes

  • File really missing. The path points to a file that was never created, moved, or deleted.
  • Wrong path. Typo in filename or folder, or wrong extension (e.g. data instead of data.txt).
  • Relative path + wrong working directory. You run the script from a different folder (e.g. project root vs. subfolder), so 'data.txt' is looked up in the wrong place. See reading files for patterns.
  • Permissions. If the OS denies access, you may see PermissionError instead.

Example that causes the error

with open('data.txt', 'r') as f:  # FileNotFoundError if data.txt isn't there
    content = f.read()

Fix 1: check if the file exists first

import os

if os.path.exists('data.txt'):
    with open('data.txt', 'r') as f:
        content = f.read()
else:
    print("File not found!")

Fix 2: use try-except

Handle the error when opening is optional or you want to give a clear message.

try:
    with open('data.txt', 'r') as f:
        content = f.read()
except FileNotFoundError:
    print("File 'data.txt' not found. Check the path and working directory.")

Fix 3: understand the current working directory

Relative paths are resolved from the current working directory. If you run the script from another folder, the same relative path can point to a different place or nothing.

import os
print(os.getcwd())  # Where Python is looking for relative paths

# Option: use an absolute path when you know the full path:
# file_path = r'C:\Users\You\Documents\data.txt'  # Windows
# file_path = '/home/user/data.txt'               # Linux/Mac
# with open(file_path, 'r') as f:
#     content = f.read()

Path relative to the script file

To build a path relative to the script’s directory (not the current working directory), use __file__:

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:
    content = f.read()

Next steps: Errors & Exceptions · PermissionError · Read CSV