
Whenever Python asks the operating system to open, read, stat, execute, or delete a file path and the OS kernel reports that the path (or one of its parent directories) does not exist (errno.ENOENT), Python halts with: FileNotFoundError: [Errno 2] No such file or directory: 'data.csv'
In practice, this exception comes from one of six mistakes:
- Relative Paths,
os.chdir()Shifts, or Missing Docker/Git Files (open("data.csv")): Python resolves relative paths against the process’s current working directory (Path.cwd())—not the directory where your.pyscript lives (__file__). It also fails in production whenos.chdir()changed the working directory mid-script, a Docker volume was not mounted, an untracked local file was excluded by.gitignore/.dockerignore, or filename casing (Data.csvvs.data.csv) differs on a case-sensitive filesystem. - Writing, Copying, or Moving a File Into a Nonexistent Parent Directory (
open("logs/2026/app.log", "w")orshutil.copy()): While mode"w"creates a missing file, it never creates missing parent directories (logs/2026/). - Unexpanded
~(open("~/data.csv")), Windows Backslash Escapes ("C:\new\data.csv"), Trailing Line Endings (\r\n), or Double Extensions (data.csv.txt): Python’sopen()does not expand~to your home directory automatically, unescaped\nor\tinside Windows path strings turns into newline or tab characters, and unstripped lines read from a file orinput()keep a trailing\n. subprocess.run()Command-String,PATH, orcwd=Mistakes (subprocess.run("git status")): On POSIX (Linux/macOS), passing a multi-word string tosubprocess.run()withoutshell=Truetells the OS to look for an executable literally named"git status"; across all platforms, it also fails when the executable is missing fromPATHor (on POSIX) whencwd=points to a nonexistent directory.- Iterating
os.listdir(folder)and Opening the Bare Filename:os.listdir("invoices")returns"inv_01.pdf", not"invoices/inv_01.pdf", soopen(name)looks in the current working directory instead of"invoices/". - Broken Symbolic Links or Race Conditions (TOCTOU): Opening a symlink whose target file was deleted, or deleting a file without
missing_ok=Truewhen another process already removed it.
Reading the FileNotFoundError: [Errno 2] Traceback
Read the traceback from the bottom up. Consider this 3-line script (/var/www/app/main.py):
from pathlib import Path
raw_text = Path("config/settings.json").read_text(encoding="utf-8")When you run /var/www/app/main.py from a directory that does not contain config/settings.json, Python prints the failing path after the colon:
Traceback (most recent call last):
File "/var/www/app/main.py", line 3, in <module>
raw_text = Path("config/settings.json").read_text(encoding="utf-8")
File "/usr/local/lib/python3.10/pathlib.py", line 1134, in read_text
with self.open(mode='r', encoding=encoding, errors=errors) as f:
File "/usr/local/lib/python3.10/pathlib.py", line 1119, in open
return self._accessor.open(self, mode, buffering, encoding, errors,
FileNotFoundError: [Errno 2] No such file or directory: 'config/settings.json'Useful OSError Attributes on FileNotFoundError
Introduced in Python 3.3 (PEP 3151), FileNotFoundError is a subclass of OSError. When you catch except FileNotFoundError as exc:, you can inspect four attributes on the exception instance (all of which are optional and default to None if FileNotFoundError was raised manually without OS arguments):
exc.errno: The integer POSIX error code (2, matchingerrno.ENOENT, when raised by an OS syscall).exc.strerror: The OS error message ('No such file or directory').exc.filename: On single-path operations (open(),os.stat(),shutil.copy(), orshutil.move()when falling back toshutil.copy2()), this holds the path that failed ('config/settings.json'). On direct two-path OS syscalls (os.rename(src, dst),os.replace(src, dst),os.link(src, dst)),exc.filenameis always set tosrc.exc.filename2: Populated withdston direct two-path OS syscalls likeos.rename(src, dst)oros.replace(src, dst)(whethersrcordst‘s parent directory was missing). On single-path calls—and onshutil.move(src_file, dst)whenos.rename()fails and falls back toshutil.copy2()—exc.filename2isNone.
(Insert this Trust Block into a Group with a light gray background inside the Traceback / Quick Fix section)
Tested Environment: Standard-library path, symlink,
os.chdir(),shutil, andsubprocesschecks verified on both Python 3.10.16 and Python 3.11.2 (Linux); optional Pandas 2.0.0 checks (pd.read_csv()andDataFrame.to_csv()) verified on Python 3.10.16. WindowsCreateProcess/ directory-permission behavior and static linter diagnostics noted from official documentation.Part of: The Ultimate Python Debugging Guide
⚡ The Quick Fix: Anchor Paths to __file__, Create Parent Folders, or Fix subprocess
Match your crashing code to one of these four fixes:
If Opening a File Next to Your .py Script (open("data.csv") or pd.read_csv("data.csv")): Anchor the Path to Path(__file__).resolve().parent
from pathlib import Path
# Fails whenever you run the script from a different working directory:
# with open("config/settings.json", encoding="utf-8") as f: ...
# Fix: Build an absolute path anchored to the directory containing this .py file
BASE_DIR = Path(__file__).resolve().parent
config_path = BASE_DIR / "config" / "settings.json"
with config_path.open(encoding="utf-8") as f:
data = f.read()(💡 Two Edge Cases for __file__: First, __file__ is only defined inside .py files—in an interactive REPL or unsaved Jupyter cell, anchor paths using Path.cwd(). Second, .resolve() follows symbolic links; if app.py is a symlink and you want the symlink’s own directory rather than the target file’s directory, use Path(__file__).parent.absolute() instead of .resolve().)
- If Writing or Copying a File (
open(..., "w"),shutil.copy(),df.to_csv()) Failed: Create the Parent Directory First
from pathlib import Path
out_file = Path("output/2026/november/report.csv")
# Fails if 'output/2026/november/' does not exist yet:
# out_file.write_text("id,total\n1,50\n", encoding="utf-8")
# Fix: Create all missing parent directories first with parents=True, exist_ok=True
out_file.parent.mkdir(parents=True, exist_ok=True)
out_file.write_text("id,total\n1,50\n", encoding="utf-8")- If the Path Starts With
~(~/data.csv) or Uses Windows Backslashes ("C:\new\data.csv"): Expand~or UsePath/ Raw Strings
from pathlib import Path
# Fails: Python looks for a literal folder named '~' in the current directory!
# p = Path("~/Downloads/report.csv").read_text(encoding="utf-8")
# Fix 1: Call .expanduser() to resolve '~' to the user's home directory
csv_path = Path("~/Downloads/report.csv").expanduser()
# Fix 2: On Windows, use forward slashes ("C:/new/data.csv") or a raw string r"C:\new\data.csv"
# so '\n' in '\new' is not turned into a newline character!
win_path = Path(r"C:\new\data.csv")- If
subprocess.run()RaisedFileNotFoundError: Pass a List of Arguments (["git", "status"])
import shutil, subprocess
# Fails on Linux/macOS (POSIX): Without shell=True, Python looks for a binary literally named "git status"!
# subprocess.run("git status", check=True)
# Fix: Pass the command and its arguments as separate strings in a list (portable across all OSes)
if shutil.which("git") is not None:
subprocess.run(["git", "status"], check=True)⏱️ The 10-Second Diagnostic: What Your FileNotFoundError Looks Like
Find the code pattern from your traceback to grab the exact fix:
| What the Crashing Line Looks Like | Why the Path Was Not Found | The Exact Fix |
|---|---|---|
| open(“data.csv”) or pd.read_csv(“data.csv”) (relative path in a script, cron job, or IDE) | Relative paths resolve against os.getcwd() (which may also shift if os.chdir() ran). | Anchor to the script folder: Path(__file__).resolve().parent / “data.csv” |
| open(“Data.csv”) works on Mac/Win, fails on Linux/Docker (deployment / container crash) | Linux filesystems are case-sensitive (Data.csv != data.csv), or the file is an untracked .gitignore file / unmounted Docker volume. | Match exact filename casing, check git status –ignored, and verify Docker -v volume mounts. |
| open(“out/2026/log.txt”, “w”) (or shutil.copy(“a.txt”, “out/2026/b.txt”)) | Mode “w” and shutil.copy() create the file, but fail if parent folder out/2026/ is missing. | Run Path(“out/2026”).mkdir(parents=True, exist_ok=True) before writing/copying. |
| open(“~/data.csv”) or open(line) (tilde `~` or trailing `\r\n` from a file) | open() does not expand ~, and lines read from a file keep a trailing \n (“data.csv\n”). | Use Path(line.rstrip(“\r\n”)).expanduser(). |
| open(“C:\new\test.txt”) (Windows backslash path string) | \n and \t are parsed as newline and tab escape characters inside normal strings. | Use forward slashes “C:/new/test.txt” or raw strings r”C:\new\test.txt”. |
| subprocess.run(“ls -la”) (or subprocess.run([“ffmpeg”, …], cwd=…)) | On POSIX, string command without shell=True looks for a binary named “ls -la”; or binary is not on PATH / cwd is missing. | Pass a list subprocess.run([“ls”, “-la”]) and verify binary with shutil.which(). |
| for f in os.listdir(“logs”): open(f) (looping over directory contents) | os.listdir() returns bare filenames (“a.log”) without the “logs/” directory prefix. | Use Path(“logs”).iterdir() or Path(“logs”).glob(“*.log”). |
Can You Spot Why Write Mode "w" Raised FileNotFoundError?
# Working directory is empty (/var/www/app) with open("exports/2026/summary.csv", "w", encoding="utf-8") as f: f.write("id,amount\n1,99.50\n")
Why does open("exports/2026/summary.csv", "w") raise FileNotFoundError: [Errno 2] No such file or directory even though mode "w" is supposed to create new files?
Table of contents
- Reading the FileNotFoundError: [Errno 2] Traceback
- ⚡ The Quick Fix: Anchor Paths to __file__ , Create Parent Folders, or Fix subprocess
- How Python Resolves Relative Paths & 3-Line Path Diagnostic
- Common Causes of FileNotFoundError: [Errno 2] No such file or directory
- 1. Relative Paths, os.chdir() Shifts, & Production Deployment Traps (Docker, Linux Case-Sensitivity, .gitignore )
- 2. Writing, Copying, or Moving Files When the Destination Parent Directory Does Not Exist
- 3. Unexpanded ~ ( ~/data.csv ), Windows Backslash Escapes ( \n , \t ), Line Endings ( \r\n ), & Double Extensions ( data.csv.txt )
- Can You Spot the os.listdir() Trap?
- 4. subprocess.run() / Popen() Raising FileNotFoundError ( ‘git status’ , Missing Binary, or Missing cwd= )
- 5. os.listdir() Returning Bare Filenames Without the Directory Path (Use .iterdir() or .glob() )
- 6. Broken Symbolic Links, Race Conditions (TOCTOU), & Why EAFP Beats os.path.exists()
- Comparing Sibling OSError File & Directory Exceptions
- Prevent Path and open() Bugs Before Runtime with Linters
- Worked Example: Fixing Relative Path & Missing Parent Directory Crashes
- Frequently Asked Questions
- Official Documentation & Related Fixes
How Python Resolves Relative Paths & 3-Line Path Diagnostic
Path.cwd() (Current Working Directory) vs. __file__ (Script Location)
When you pass a relative path like "data/users.csv" to open(), pathlib.Path(), or pd.read_csv(), Python does not look relative to the folder where your .py script is saved. Instead, the operating system resolves relative paths against the Current Working Directory (os.getcwd() / Path.cwd())—which is whichever folder your terminal, IDE, cron daemon, or Docker entrypoint was standing in when it launched python!
Suppose your project has this layout:
/var/www/project/
├── data/
│ └── users.csv
└── src/
└── app.py <-- Contains: open("data/users.csv")- If you run
cd /var/www/project && python src/app.py,Path.cwd()is/var/www/project(succeeds). - If you run
cd /var/www/project/src && python app.py,Path.cwd()is/var/www/project/src(crashes withFileNotFoundError).
3-Line Diagnostic Snippet to Inspect a Failing Path
When a file lookup fails and you aren’t sure where Python is actually looking, drop these three lines right above the crash:
from pathlib import Path
target = Path("config/settings.json").expanduser()
print("1. Current working dir (cwd):", Path.cwd())
print("2. Target resolved path: ", target.resolve())
print("3. Parent exists?:", target.parent.exists(), "| Sibling files:", [p.name for p in target.parent.glob("*")] if target.parent.exists() else "N/A")Common Causes of FileNotFoundError: [Errno 2] No such file or directory
Here are the six primary causes of this error and how to fix each one permanently.
1. Relative Paths, os.chdir() Shifts, & Production Deployment Traps (Docker, Linux Case-Sensitivity, .gitignore)
Relative paths work on a developer’s laptop when launched from a specific folder, then break in production or CI for five reasons:
- Launching the Script From a Different Working Directory: In VS Code, PyCharm, cron jobs, systemd units, and pytest runs,
Path.cwd()is frequently the repository root (or/rootin cron) rather than the subfolder containing your script. Anchor relative paths toPath(__file__).resolve().parent:
from pathlib import Path # 1. Directory containing the current .py script (follows symlinks): SCRIPT_DIR = Path(__file__).resolve().parent # (Note: If __file__ is a symlink and you want the symlink's own directory, # use Path(__file__).parent.absolute() instead of .resolve()!) # 2. Anchor sibling or parent paths to SCRIPT_DIR: local_csv = SCRIPT_DIR / "data" / "users.csv" project_root_csv = SCRIPT_DIR.parent / "data" / "users.csv"
- (💡 Loading Installed Package Data Files (
importlib.resources.files()): If you are packaging a library for installation viapip, useimportlib.resources.files("my_pkg").joinpath("data.json").read_text(encoding="utf-8"). As documented in the Officialimportlib.resourcesDocs,files()was introduced in Python 3.9 to replace the legacyread_text()/path()functions—which were deprecated in Python 3.11—and in Python 3.12+files()can even be called with no arguments to target the caller’s package.) os.chdir()Changing the Working Directory Mid-Script: If an earlier function or helper library callsos.chdir("/tmp/work")mid-execution, the process-wide working directory changes! A relative pathopen("data/sales.csv")that worked at the top of your script will suddenly raiseFileNotFoundErrorafteros.chdir()runs. Anchoring paths toSCRIPT_DIRmakes your code immune toos.chdir().- Docker Containers & Missing Volume Mounts: Inside a Docker container, the container has an isolated filesystem. If your script tries to open
/home/ubuntu/data.csvfrom the host machine—or a file inside/app/uploads/when you forgot to mount the volume (docker run -v /host/uploads:/app/uploads) or excluded the file in.dockerignore—Python raisesFileNotFoundError. - Filesystem Case Sensitivity (
Data.csvvs.data.csvon Linux vs. Windows/macOS): Windows (NTFS) and macOS (APFS by default) are case-insensitive, soopen("Data.csv")opensdata.csvwithout complaint on your laptop. Standard Linux filesystems (ext4/xfsin Docker, AWS, and GitHub Actions) are case-sensitive, soopen("Data.csv")immediately crashes withFileNotFoundErrorin production! - Untracked
.gitignoreFiles (.env,credentials.json, Local Datasets): Untracked local files that match.gitignoreexist on your development machine but are never staged or pushed to Git, causing CI pipelines and production servers to fail withFileNotFoundErroron checkout. (Note:.gitignoreonly affects untracked files—if a file was already committed to Git before being added to.gitignore, Git continues tracking and deploying it unless you remove it from the index withgit rm --cached <file>.)
2. Writing, Copying, or Moving Files When the Destination Parent Directory Does Not Exist
A common surprise is seeing FileNotFoundError (or OSError) on a line that writes, copies, or moves a file—such as open("reports/2026/out.txt", "w"), shutil.copy("src.csv", "reports/2026/out.csv"), or df.to_csv("reports/2026/out.csv").
Look at what each operation creates—and the exact exception it raises when the destination parent directory is missing:
| Operation / Mode | Creates Missing Leaf File? | Creates Missing Parent Directories? | Exact Behavior When Destination Parent Folder Is Missing & Fix |
open(path, "r") (default read mode) | No | No | Raises FileNotFoundError. Anchor path to __file__. |
open(path, "w") / "a" / "x" | Yes (creates leaf file) | No | Raises FileNotFoundError. Run Path(path).parent.mkdir(parents=True, exist_ok=True) first. |
shutil.copy(src, dst) / os.rename(src, dst) | Yes (copy creates dst; rename moves src) | No | Raises FileNotFoundError if src or dst.parent is missing. Create Path(dst).parent.mkdir(parents=True, exist_ok=True) first. |
shutil.move(src, dst) | Moves src to dst (or into dst/ if dst is an existing dir) | No for files (Yes if src is a directory!) | When src is a file, missing dst.parent fails in os.rename(), falls back to shutil.copy2(), and raises FileNotFoundError (whereas if src is a directory, the fallback shutil.copytree() creates dst.parent). Always create Path(dst).parent.mkdir(parents=True, exist_ok=True) before moving files! |
pd.DataFrame.to_csv(path) (or .to_parquet()) | Yes (creates leaf file) | No | Pre-checks parent folder and raises base OSError: Cannot save file into a non-existent directory (whereas pd.read_csv() raises FileNotFoundError). Create Path(path).parent.mkdir(parents=True, exist_ok=True) first. |
Path(dir_path).mkdir() | N/A (creates 1 folder) | No (unless parents=True) | Raises FileNotFoundError. Pass parents=True, exist_ok=True. |
3. Unexpanded ~ (~/data.csv), Windows Backslash Escapes (\n, \t), Line Endings (\r\n), & Double Extensions (data.csv.txt)
Four path-formatting mistakes cause Python to look for a completely different filename than the one you intended:
- Unexpanded Tilde (
~) or Environment Variables ($HOME): In a terminal shell,~/data.csvexpands to/home/alice/data.csv. In Python,open("~/data.csv")andPath("~/data.csv").open()treat~as a literal folder name (./~/data.csv)! Always call.expanduser()(andos.path.expandvars()if the path string contains$VARor%VAR%):
import os
from pathlib import Path
# Expands '~' to /home/user (or C:\Users\user on Windows):
safe_path = Path(os.path.expandvars("~/data/metrics.csv")).expanduser()2. Unescaped Backslashes in Windows Paths ("C:\new\temp\table.csv"): In a standard Python string literal, \n is a newline character (0x0a), \t is a tab (0x09), and \r is a carriage return! Writing open("C:\new\table.csv") embeds an actual newline and tab in the filename!
- Fix: Either use
pathlib.Path("C:/new/table.csv")with forward slashes, or prefix Windows string literals withrto make them raw strings (r"C:\new\table.csv"). (Note: A raw string cannot end with an odd number of backslashes liker"C:\new\".)
3. Trailing Line Endings (\r\n) From Manifest Files vs. .strip() on User Input: When you read file paths line-by-line from a text file or sys.stdin.readline(), each line ends with \n or \r\n ("data/sales.csv\n"), causing open() to look for a filename ending in a newline character!
- Use
.rstrip("\r\n")for file/stream lines: Callingline.rstrip("\r\n")removes only the trailing CR/LF line terminator without corrupting valid filenames or directory names that legitimately contain a leading or trailing space (" "). - Use
.strip()only when trimming interactive human input (input().strip()): If a human user typed accidental spaces around a path at a prompt,.strip()removes both spaces and newlines:
# Reading a path from a manifest file (preserves any valid spaces in the filename):
manifest_line = "data/sales.csv\r\n"
clean_path = Path(manifest_line.rstrip("\r\n"))4. Hidden Double File Extensions (data.csv.txt): On Windows File Explorer and macOS Finder, when “Hide extensions for known file types” is enabled, a file saved in Notepad or TextEdit as data.csv is often actually named data.csv.txt on disk! Run list(Path(".").glob("data*")) to see the true extension.
Can You Spot the os.listdir() Trap?
import os for filename in os.listdir("invoices"): with open(filename, encoding="utf-8") as f: print(f.readline())
The folder invoices/ exists and contains inv_01.txt, yet line 4 raises FileNotFoundError: [Errno 2] No such file or directory: 'inv_01.txt'. Why?
4. subprocess.run() / Popen() Raising FileNotFoundError ('git status', Missing Binary, or Missing cwd=)
When subprocess.run() or subprocess.Popen() raises FileNotFoundError: [Errno 2] No such file or directory, it is almost never complaining about a data file—it is telling you that the OS could not launch the child process! Check these three causes:
- Passing a Multi-Word Command String Without
shell=True(subprocess.run("git status")— POSIX vs. Windows):- On POSIX (Linux/macOS): When
shell=False(the default and safest setting), a stringargsis not split on spaces—it is passed directly toos.execvp()as the literal filename of the executable! Passing"git status"(or["git status"]) searchesPATHfor a single binary file whose name literally contains a space ("git status") and raises:FileNotFoundError: [Errno 2] No such file or directory: 'git status' - On Windows:
subprocess.Popenpasses a stringargsto the Win32CreateProcessAPI, which does parse the program name from the command-line string (only raisingFileNotFoundError: [WinError 2]if the program itself is not found). However, as documented in the OfficialsubprocessDocs, you should always pass a sequence of arguments (subprocess.run(["git", "status"], check=True)) whenshell=Falseso your code works portably across Linux, macOS, and Windows.
- On POSIX (Linux/macOS): When
- The Executable Is Not Installed or Not on
PATH(ffmpeg,docker,chromedriver): Ifsubprocess.run(["ffmpeg", "-version"])raisesFileNotFoundError: [Errno 2] No such file or directory: 'ffmpeg', eitherffmpegis not installed, or the directory containingffmpeg(such as/opt/homebrew/binor/usr/local/bininside a cron/systemd environment) is not inos.environ["PATH"].- Fix: Check
shutil.which("ffmpeg")before callingsubprocess.run(), or pass the absolute binary path["/usr/local/bin/ffmpeg", "-version"]. (On Windows, running a shell built-in likedirorcopyalso requiresshell=Truebecause they arecmd.exebuilt-ins rather than standalone.exefiles.)
- Fix: Check
- Passing a Nonexistent Directory to
cwd=(subprocess.run(["ls"], cwd="/missing/dir")): On POSIX (Linux/macOS), CPython’s_posixsubprocess.fork_execcallschdir(cwd)in the child beforeexec; whencwddoes not exist (err_msg == "noexec"),subprocesssetsexc.filename = cwdand raisesFileNotFoundError: [Errno 2] No such file or directory: '/missing/dir'. (On Windows, passing a nonexistentcwdtoCreateProcessraisesNotADirectoryError: [WinError 267] The directory name is invalidinstead.)
5. os.listdir() Returning Bare Filenames Without the Directory Path (Use .iterdir() or .glob())
When you loop over a subfolder with for name in os.listdir("invoices"):, os.listdir() returns only the bare entry names (["inv_01.txt", "inv_02.txt"])—it does not include "invoices/"! Calling open(name) looks for "inv_01.txt" in your current working directory and raises FileNotFoundError.
- The Fix: Use
Path("invoices").iterdir()to iterate all entries, orPath("invoices").glob("*.txt")(and.rglob("*.txt")for recursive subdirectories) to filter by pattern while automatically preserving the"invoices/"directory prefix:
from pathlib import Path
invoices_dir = Path("invoices")
# Option 1: Iterate all files in the directory with .iterdir()
for file_path in invoices_dir.iterdir():
if file_path.is_file(): # Skips subdirectories (avoids IsADirectoryError / Windows PermissionError!)
print(file_path, "->", len(file_path.read_text(encoding="utf-8")), "chars")
# Option 2: Filter by pattern with .glob("*.txt") or recursive .rglob("*.txt")
for txt_path in invoices_dir.glob("*.txt"):
print(txt_path.name, "->", txt_path.read_text(encoding="utf-8").strip())- (⚠️ Cross-Platform Directory Trap (
IsADirectoryErrorvs. WindowsPermissionError): Always checkif file_path.is_file():when iterating directories! If a subfolder is passed toopen(), Linux and macOS raiseIsADirectoryError: [Errno 21] Is a directory, whereas Windows raisesPermissionError: [Errno 13] Permission denied!)
6. Broken Symbolic Links, Race Conditions (TOCTOU), & Why EAFP Beats os.path.exists()
Sometimes os.listdir() shows a file right there in the directory, yet open(path) still raises FileNotFoundError! That happens in two scenarios:
- Broken Symbolic Links (
path.is_symlink() == Trueandpath.exists() == False): Iflatest.logis a symbolic link pointing toapp_2026_11_01.log, andapp_2026_11_01.logwas deleted, the symlink entrylatest.logstill sits in the folder (os.path.lexists("latest.log")andPath("latest.log").is_symlink()areTrue), but following the link withopen("latest.log")raisesFileNotFoundErrorbecause the target file is gone! - Race Conditions (TOCTOU) & Safe File Deletion (
unlink(missing_ok=True)): In multi-process apps or web workers, checkingif path.exists(): open(path)(Look Before You Leap / LBYL) is vulnerable to a Time-of-Check to Time-of-Use (TOCTOU) race condition if another worker deletes the file between.exists()andopen().- For Reading Files (EAFP): Open the file directly inside a
try ... except FileNotFoundError:block without calling.exists()first. - For Deleting Temporary Files: Instead of a two-step
if os.path.exists(p): os.remove(p)check, usePath(p).unlink(missing_ok=True)(Python 3.8+), which avoids the check-then-delete TOCTOU race condition by callingos.unlink()directly and suppressingFileNotFoundErrorinternally.
- For Reading Files (EAFP): Open the file directly inside a
Comparing Sibling OSError File & Directory Exceptions
Since PEP 3151 (Python 3.3+), Python maps specific OS errno codes to dedicated OSError subclasses:
| Exception Message | POSIX errno | Why It Happened & The Exact Fix |
FileNotFoundError: [Errno 2] No such file or directory | ENOENT (2) | File, parent directory, symlink target, or subprocess binary does not exist. Anchor paths to __file__ or create parent dirs with .mkdir(parents=True, exist_ok=True). |
OSError: Cannot save file into a non-existent directory | None (Pandas check) | Raised by Pandas df.to_csv() / df.to_parquet() when the parent directory does not exist. Create Path(path).parent.mkdir(parents=True, exist_ok=True) first. |
IsADirectoryError: [Errno 21] Is a directory | EISDIR (21) | Passed a directory path (open("invoices/")) to open() on Linux/macOS. Filter with if path.is_file(): before opening. |
PermissionError: [Errno 13] Permission denied | EACCES / EPERM (13 / 1) | Process lacks OS permissions—or on Windows, you passed a directory path (open("invoices/")) to open()! Check path.is_file() and file permissions. |
NotADirectoryError: [Errno 20] Not a directory | ENOTDIR (20) | Tried to treat a regular file as a parent folder (open("data.csv/sub.txt")), or passed a missing cwd to subprocess.run() on Windows ([WinError 267]). |
FileExistsError: [Errno 17] File exists | EEXIST (17) | Called open(p, "x") or Path(d).mkdir() when the file or folder already exists. Pass exist_ok=True to .mkdir(). |
Prevent Path and open() Bugs Before Runtime with Linters
Modern Python linters include dedicated rules that flag unsafe open() calls and encourage pathlib best practices (representative diagnostics noted from official documentation):
- Ruff / Pylint (
PLW1514unspecified-encoding): Flagsopen("data.txt")calls that omitencoding="utf-8". - Ruff (
flake8-use-pathlibPTHrules): Flags legacyos.pathpatterns (PTH100–PTH123) so you can standardize onpathlib.Path.
ruff check --select PTH,PLW1514 main.py
Worked Example: Fixing Relative Path & Missing Parent Directory Crashes
Let’s walk through a script (/var/www/app/src/report.py) that reads data/sales.csv and writes a summary to exports/2026/summary.txt—hitting FileNotFoundError on both the read and the write.
The Crashing Code (/var/www/app/src/report.py):
from pathlib import Path
def generate_summary() -> None:
# Bug 1: Relative path fails whenever Python is launched outside /var/www/app/src!
raw = Path("data/sales.csv").read_text(encoding="utf-8")
# Bug 2: 'exports/2026/' directory does not exist yet!
out_path = Path("exports/2026/summary.txt")
out_path.write_text(f"Lines: {len(raw.splitlines())}\n", encoding="utf-8")
generate_summary()Traceback:
Traceback (most recent call last):
File "/var/www/app/src/report.py", line 11, in <module>
generate_summary()
File "/var/www/app/src/report.py", line 5, in generate_summary
raw = Path("data/sales.csv").read_text(encoding="utf-8")
File "/usr/local/lib/python3.10/pathlib.py", line 1134, in read_text
with self.open(mode='r', encoding=encoding, errors=errors) as f:
File "/usr/local/lib/python3.10/pathlib.py", line 1119, in open
return self._accessor.open(self, mode, buffering, encoding, errors,
FileNotFoundError: [Errno 2] No such file or directory: 'data/sales.csv'The Fix: Anchor BASE_DIR to Path(__file__).resolve().parent, and call out_path.parent.mkdir(parents=True, exist_ok=True) before writing summary.txt:
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent
def generate_summary() -> str:
in_path = BASE_DIR / "data" / "sales.csv"
raw = in_path.read_text(encoding="utf-8")
out_path = BASE_DIR / "exports" / "2026" / "summary.txt"
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(f"Lines: {len(raw.splitlines())}\n", encoding="utf-8")
return out_path.read_text(encoding="utf-8").strip()
print(generate_summary())
# Output:
# Lines: 3Representative Verification Script (Standard Library + Optional Pandas Check)
You can run this self-contained verification script to test all six causes and their working fixes:
- Part 1 (Standard Library & OS Path Mechanics — Verified on Python 3.10.16 and Python 3.11.2): Uses only the Python standard library and
tempfile.TemporaryDirectory()to verifyOSErrorattributes (errno.ENOENT,.filename,.filename2), relative paths failing whencwdchanges vs.Path(__file__).resolve().parent, symlinked script resolution (.resolve().parentvs..parent.absolute()), filesystem case sensitivity (Sales.csvvs.sales.csv, probed dynamically so it will not false-fail on case-insensitive macOS/Windows drives), mid-scriptos.chdir()breaking relative paths, write mode"w",shutil.copy(), andshutil.move()(on a file) failing on missing destination parent folders vs..parent.mkdir(parents=True, exist_ok=True), leading~failing inPath("~/...")vs..expanduser(),.rstrip("\r\n")preserving legitimate filename spaces while stripping line endings,subprocess.run()string command and missingcwd=(on POSIX), the exactfor bare_name in os.listdir("invoices"): open(bare_name)failure incwdvs.Path.iterdir()andPath.glob()/Path.rglob(), broken symlinks, andPath.unlink(missing_ok=True). - Part 2 (Optional Pandas Check — Verified on Python 3.10.16 with Pandas 2.0.0; skipped if Pandas is not installed): Verifies
pd.read_csv()raisingFileNotFoundErroranddf.to_csv()raisingOSError("Cannot save file into a non-existent directory")when the parent folder is missing, and both succeeding oncemkdir(parents=True, exist_ok=True)is called.
import errno, importlib.resources, os, shutil, subprocess, sys, tempfile
from pathlib import Path
def assert_file_not_found(fn, expected_filename=None):
try:
fn()
except FileNotFoundError as exc:
assert exc.errno == errno.ENOENT
if expected_filename is not None:
assert expected_filename in str(exc.filename), f"Expected {expected_filename!r} in {exc.filename!r}"
return exc
else:
raise AssertionError("Expected FileNotFoundError was not raised")
# =====================================================================
# PART 1: Standard-Library & OS Path Mechanics (No external packages)
# =====================================================================
with tempfile.TemporaryDirectory() as tmp:
tmp_path = Path(tmp).resolve()
# 1A. Relative path failing when working directory differs from script directory (__file__)
# + symlinked script difference (.resolve().parent vs .parent.absolute())
app_dir = tmp_path / "app"
data_dir = app_dir / "data"
data_dir.mkdir(parents=True)
(data_dir / "sales.csv").write_text("id,amount\n1,50\n2,75\n", encoding="utf-8")
script_file = app_dir / "report.py"
script_file.write_text(
"from pathlib import Path\n"
"import sys\n"
"mode = sys.argv[1]\n"
"if mode == 'bad':\n"
" Path('data/sales.csv').read_text(encoding='utf-8')\n"
"else:\n"
" base = Path(__file__).resolve().parent\n"
" print(len((base / 'data' / 'sales.csv').read_text(encoding='utf-8').splitlines()))\n",
encoding="utf-8",
)
r_bad = subprocess.run([sys.executable, str(script_file), "bad"], cwd=tmp_path, capture_output=True, text=True)
assert "FileNotFoundError: [Errno 2] No such file or directory: 'data/sales.csv'" in r_bad.stderr
r_good = subprocess.run([sys.executable, str(script_file), "good"], cwd=tmp_path, capture_output=True, text=True)
assert r_good.stdout.strip() == "3"
# Symlinked script check: .resolve().parent vs .parent.absolute()
bin_dir = tmp_path / "bin_links"
bin_dir.mkdir()
symlink_script = bin_dir / "report_link.py"
symlink_script.symlink_to(script_file)
assert symlink_script.resolve().parent == app_dir
assert symlink_script.parent.absolute() == bin_dir
# Filesystem case-sensitivity check (probes whether the underlying filesystem is
# actually case-sensitive first, avoiding false failures on macOS APFS or Windows):
is_case_sensitive_fs = not (data_dir / "Sales.csv").exists()
if is_case_sensitive_fs:
assert_file_not_found(lambda: (data_dir / "Sales.csv").read_text(encoding="utf-8"), "Sales.csv")
# 1B. os.chdir() mid-script breaking relative paths while anchored paths still work
orig_cwd = Path.cwd()
try:
os.chdir(app_dir)
assert Path("data/sales.csv").exists() is True
anchored_sales = Path("data/sales.csv").resolve()
os.chdir(tmp_path) # Mid-script working directory change!
assert_file_not_found(lambda: Path("data/sales.csv").read_text(encoding="utf-8"), "data/sales.csv")
assert len(anchored_sales.read_text(encoding="utf-8").splitlines()) == 3
finally:
os.chdir(orig_cwd)
# 1C. Write mode "w", shutil.copy(), and shutil.move() (on a file) fail when destination parent is missing
nested_out = tmp_path / "exports" / "2026" / "summary.txt"
assert_file_not_found(lambda: nested_out.write_text("ok", encoding="utf-8"), "summary.txt")
assert_file_not_found(
lambda: shutil.copy(data_dir / "sales.csv", tmp_path / "missing_backup" / "sales.csv"),
"sales.csv",
)
assert_file_not_found(
lambda: shutil.move(str(data_dir / "sales.csv"), str(tmp_path / "missing_move_parent" / "sales.csv")),
"sales.csv",
)
nested_out.parent.mkdir(parents=True, exist_ok=True)
nested_out.write_text("ok", encoding="utf-8")
shutil.copy(data_dir / "sales.csv", nested_out.parent / "sales_copy.csv")
assert nested_out.read_text(encoding="utf-8") == "ok"
assert (nested_out.parent / "sales_copy.csv").exists()
# 1D. Direct '~' at start of path vs .expanduser(), .rstrip("\r\n") vs .strip(), & filename2 on os.rename()
fake_home = tmp_path / "fake_home"
fake_home.mkdir()
(fake_home / "profile.txt").write_text("user=alice", encoding="utf-8")
old_home = os.environ.get("HOME")
try:
os.environ["HOME"] = str(fake_home)
assert_file_not_found(lambda: Path("~/profile.txt").read_text(encoding="utf-8"), "~/profile.txt")
assert Path("~/profile.txt").expanduser().read_text(encoding="utf-8") == "user=alice"
finally:
if old_home is not None:
os.environ["HOME"] = old_home
# Line-ending stripping with .rstrip("\r\n") (preserves intentional spaces while removing \r\n):
spaced_file = data_dir / " space_name.csv"
spaced_file.write_text("ok", encoding="utf-8")
line_from_manifest = f"{spaced_file}\r\n"
assert_file_not_found(lambda: Path(line_from_manifest).read_text(encoding="utf-8"))
assert Path(line_from_manifest.rstrip("\r\n")).read_text(encoding="utf-8") == "ok"
exc_ren = assert_file_not_found(lambda: os.rename(nested_out, tmp_path / "missing_dir" / "summary.txt"))
assert str(nested_out) in str(exc_ren.filename) and "summary.txt" in str(exc_ren.filename2)
# 1E. subprocess.run() with a multi-word string command (POSIX shell=False) & missing cwd= directory
if os.name == "posix":
assert_file_not_found(lambda: subprocess.run("python --version"), "python --version")
missing_cwd = tmp_path / "nonexistent_cwd"
assert_file_not_found(
lambda: subprocess.run([sys.executable, "-c", "pass"], cwd=missing_cwd),
"nonexistent_cwd",
)
r_sub = subprocess.run([sys.executable, "-c", "print('sub_ok')"], capture_output=True, text=True, check=True)
assert r_sub.stdout.strip() == "sub_ok"
# 1F. Exact os.listdir() bare-filename failure (`open(bare_name)` in cwd) vs Path.iterdir() / Path.glob()
inv_dir = tmp_path / "invoices"
inv_dir.mkdir()
(inv_dir / "inv_01.txt").write_text("paid", encoding="utf-8")
orig_cwd = Path.cwd()
try:
os.chdir(tmp_path)
for bare_name in os.listdir("invoices"):
assert bare_name == "inv_01.txt"
# Opening bare_name directly looks in cwd (tmp_path) instead of tmp_path/invoices:
assert_file_not_found(lambda: open(bare_name, encoding="utf-8"), "inv_01.txt")
assert [p.read_text(encoding="utf-8") for p in Path("invoices").iterdir()] == ["paid"]
assert [p.read_text(encoding="utf-8") for p in Path("invoices").glob("*.txt")] == ["paid"]
assert [p.read_text(encoding="utf-8") for p in Path(".").rglob("inv_*.txt")] == ["paid"]
finally:
os.chdir(orig_cwd)
# 1G. Broken symlink & Path.unlink(missing_ok=True)
broken_link = tmp_path / "broken_link.txt"
broken_link.symlink_to(tmp_path / "deleted_target.txt")
assert broken_link.is_symlink() is True and broken_link.exists() is False
assert_file_not_found(lambda: broken_link.read_text(encoding="utf-8"))
broken_link.unlink(missing_ok=True)
broken_link.unlink(missing_ok=True)
print(f"[OK] Part 1: All standard-library FileNotFoundError checks passed on Python {sys.version.split()[0]}!")
# =====================================================================
# PART 2: Optional Pandas Check (pd.read_csv -> FileNotFoundError vs
# DataFrame.to_csv -> OSError on missing parent directory)
# =====================================================================
try:
import pandas as pd
except ImportError:
print("[SKIP] pandas not installed in this interpreter")
else:
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "missing_folder" / "data.csv"
# 1. pd.read_csv() on a missing path raises FileNotFoundError:
assert_file_not_found(lambda: pd.read_csv(p))
# 2. DataFrame.to_csv() on a missing parent folder raises OSError ("Cannot save file into a non-existent directory"):
try:
pd.DataFrame({"a": [1, 2]}).to_csv(p, index=False)
except OSError as exc:
assert "Cannot save file into a non-existent directory" in str(exc)
else:
raise AssertionError("Expected OSError from to_csv on missing parent directory")
# 3. Creating the parent directory fixes both to_csv() and read_csv():
p.parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame({"a": [1, 2]}).to_csv(p, index=False)
df_loaded = pd.read_csv(p)
assert df_loaded["a"].tolist() == [1, 2]
print(f"[OK] Part 2: pandas {pd.__version__} check passed on Python {sys.version.split()[0]}!")Can You Fix This subprocess.run() FileNotFoundError?
import subprocess subprocess.run("python --version", check=True)
Why does subprocess.run("python --version", check=True) raise FileNotFoundError: [Errno 2] No such file or directory: 'python --version' on Linux/macOS?
Frequently Asked Questions
FileNotFoundError: [Errno 2] No such file or directory when the file is in the same folder as my script?Python resolves relative paths (like open("data.csv")) against the current working directory (os.getcwd()), not the directory where your .py script is saved. If you run the script from a parent folder, an IDE workspace root, or after os.chdir() changed the working directory, Python looks in that other folder. Anchor the path to your script’s directory using Path(__file__).resolve().parent / "data.csv".
FileNotFoundError in Docker or Linux production?Check three deployment differences: (1) Case sensitivity—Windows and macOS are case-insensitive by default, whereas standard Linux filesystems (ext4/xfs) treat Data.csv and data.csv as completely different files; (2) Unmounted Docker volumes or .dockerignore—files on the host machine are not inside the container unless mounted with -v or copied via COPY; and (3) Untracked .gitignore files—untracked local config or data files matched by .gitignore are never committed to Git.
open("folder/file.txt", "w") or shutil.copy("a.txt", "folder/b.txt") raise FileNotFoundError?Write mode "w" (as well as "a", "x", shutil.copy(), and shutil.move() when moving a file) will create the leaf file if folder/ already exists, but the OS never automatically creates missing parent directories. (Similarly, Pandas’ df.to_csv("folder/out.csv") raises OSError: Cannot save file into a non-existent directory.) Create the parent directory first with Path("folder/file.txt").parent.mkdir(parents=True, exist_ok=True).
open("~/data.csv") raise FileNotFoundError?Unlike a Bash or Zsh terminal, Python’s open() does not automatically expand ~ to your home directory—it looks for a literal subfolder named '~' in the current working directory. Call Path("~/data.csv").expanduser() (or os.path.expanduser("~/data.csv")) first.
subprocess.run("git status") raise FileNotFoundError: [Errno 2] No such file or directory: 'git status' on Linux/macOS?On POSIX systems when shell=False (the default), subprocess.run() does not split a string command on spaces—it passes the entire string to os.execvp() as the literal filename of a single executable binary. Pass the command and its arguments as a list of strings: subprocess.run(["git", "status"], check=True).
FileNotFoundError if it doesn’t exist?Use Path("temp.txt").unlink(missing_ok=True) (available since Python 3.8). With missing_ok=True, Python calls os.unlink() directly and suppresses FileNotFoundError if the file was already removed.
Official Documentation & Related Fixes
- Master Guide: The Ultimate Python Debugging Guide: Tracebacks, Exceptions, and Fixes
- Related Error: How to Fix ModuleNotFoundError: No module named ‘x’
- Related Error: How to Fix ImportError: attempted relative import with no known parent package
- Official Python Docs —
FileNotFoundError&OSError: Built-in Exceptions —FileNotFoundError - Official Python Docs —
pathlibObject-Oriented Paths: Standard Library —pathlib - Official Python Docs —
open()Built-in Function: Built-in Functions —open() - Official Python Docs —
subprocess.run(): Standard Library —subprocess

