FileNotFoundError, what it means and how to fix it

The operating system looked for the path in the message and found nothing there. The file usually exists; the path the program used does not point at it. The dominant cause is the working directory: a relative path like data.csv is resolved against the folder the program was launched from, not the folder the script lives in, and those differ in editors, schedulers, and double-clicked launches.

What it looks like

open("data.csv")        # looked for in the *working directory*

Traceback (most recent call last):
  File "main.py", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'

# fixed: build the path from the script's own folder
from pathlib import Path
open(Path(__file__).parent / "data.csv")

The fix, in order

  1. Print the working directory and the absolute path. Add import os; print(os.getcwd()) and print(os.path.abspath(path)). The mismatch between where you think the program runs and where it actually runs explains most cases instantly.
  2. Anchor paths to the script, not the launch folder. Path(__file__).parent / "data.csv" finds the file next to the script no matter how the program was started.
  3. Check spelling, case, and the real extension. Linux and macOS treat Data.csv and data.csv as different files, and Windows hides extensions, so the file may really be data.csv.txt.
  4. On Windows paths, use raw strings or forward slashes. "C:\Users\..." written normally contains escape sequences (\n, \t) that corrupt the path; write r"C:\..." or use /.
  5. If the code creates the file first, check that the earlier write actually happened and went where expected, and that the containing folder exists; open() creates files, not folders.

If it still happens

If the absolute path is correct and the file is visibly there, check for trailing spaces or invisible characters in the name, a network drive that was not mounted, or (in containers and services) the program running in a different filesystem than the one you are inspecting.

Common questions

The file exists. Why does Python say it doesn't? Because existence is judged at the exact path given, resolved from the working directory. The file exists somewhere; the path did not lead to it. Printing the absolute path almost always reveals a different folder than expected.

Is FileNotFoundError only about files? No; it also fires for missing folders in a path, missing executables run through subprocess, and missing devices. In every case, some component of the path could not be found.

Related errors

PermissionError · OSError · ModuleNotFoundError