FileNotFoundError

[Errno 2] No such file or directory — the path, resolved against the current working directory, does not exist. Usually the file is there, but the cwd is not where you think.

InheritsBaseException›Exception›OSError›FileNotFoundError
OS exceptionPython 3.3+Live demo
FileNotFoundError(errnoerrno — errno.ENOENT when raised by the OS. With a single argument, errno stays None and the argument is the message.type: int · default: null, strerror[, filename])
Raised by
open(path), Path.read_text(), os.remove(), os.listdir()
Message
[Errno 2] No such file or directory: 'path'
Quick fix
build the path from Path(__file__).parent, not the cwd
Watch out
open(p, 'w') also raises it when the folder is missing

Demo

Live evaluation
report_1.txt to report_3.txt exist in the working directory. Open another one.
Try:
Inputs
nintreport number
Code
from pathlib import Path
for i in (1, 2, 3):
    Path(f'report_{i}.txt').write_text(f'report {i}')
n = 2
open(f'report_{n}.txt').read()
Result
'report 2'

The message ends with repr() of the path you passed — relative, exactly as typed, not the absolute path Python looked at. That is why the error rarely tells you the real problem: the name is right, but it was resolved against a different working directory. e.filename gives the same path unquoted.

Constructor

NameTypeRequiredDescription
errnointnoerrno.ENOENT when raised by the OS. With a single argument, errno stays None and the argument is the message.
strerrorstrnoThe OS message — 'No such file or directory' from open().
filenamestr | bytes | NonenoThe path exactly as you passed it — relative paths are not made absolute.

Attributes

AttributeTypeMeaning
errnoint | Noneerrno.ENOENT (2 on Linux, macOS and Windows) when raised by the OS.
strerrorstr | None'No such file or directory' from open(); Windows os.* calls give 'The system cannot find the file specified'.
filenamestr | bytes | NoneThe path you passed, unchanged. Resolve it yourself with os.path.abspath(e.filename) to see where Python looked.
filename2str | NoneSecond path for two-path calls like os.rename(src, dst).

Common patterns

Paths relative to the script, not the cwd
The cwd is wherever the program was started from. Anchor data files to the source file instead.
from pathlib import Path
HERE = Path(__file__).resolve().parent
config = (HERE / 'config.ini').read_text()
Optional file with a fallback
EAFP: try to read, fall back when it is absent. No race between an exists() check and the open().
try:
    with open('settings.json') as f:
        settings = json.load(f)
except FileNotFoundError:
    settings = {}
Show where Python actually looked
When debugging, print the absolute path and the cwd along with the error.
import os
try:
    f = open(path)
except FileNotFoundError as e:
    raise SystemExit(f'{os.path.abspath(e.filename)} not found (cwd: {os.getcwd()})')
Delete if present
unlink(missing_ok=True) (3.8+) swallows only the not-found case.
from pathlib import Path
Path('cache.db').unlink(missing_ok=True)

Examples

1. Missing file
open('missing.txt')
Returns
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
2. Relative paths use the cwd
import os from pathlib import Path os.mkdir('data') Path('data/users.csv').write_text('id,name') (os.path.exists('users.csv'), os.path.exists('data/users.csv'))
Returns
(False, True)
3. Change the cwd and it works
import os from pathlib import Path os.mkdir('data') Path('data/users.csv').write_text('id,name') os.chdir('data') open('users.csv').read()
Returns
'id,name'
4. e.filename is the path as given
try: open('logs/today.log') except FileNotFoundError as e: r = (e.filename, e.strerror) r
Returns
('logs/today.log', 'No such file or directory')
5. It is an OSError with errno ENOENT
import errno try: open('missing.txt') except OSError as e: r = (type(e).__name__, e.errno == errno.ENOENT) r
Returns
('FileNotFoundError', True)
6. unlink(missing_ok=True) never raises it
from pathlib import Path Path('gone.txt').unlink(missing_ok=True) Path('gone.txt').exists()
Returns
False
7. One-argument form: errno is None
e = FileNotFoundError('config.toml') (e.errno, e.filename, str(e))
Returns
(None, None, 'config.toml')

Pitfalls

1. open(p, 'w') does not create folders
Write mode creates the file but not its parent directory. A missing folder gives FileNotFoundError on the full path, which looks like the file is the problem.
Folder missing
open('logs/app.log', 'w')
FileNotFoundError: [Errno 2] No such file or directory: 'logs/app.log'
mkdir first
from pathlib import Path
Path('logs').mkdir(parents=True, exist_ok=True)
open('logs/app.log', 'w').write('started')
7
2. Relative to the cwd, not to the script
The file sits next to the code, but the program was started from the project root. The fix anchors the path to a known folder (in a real script: Path(__file__).parent).
Bare name
from pathlib import Path
Path('app').mkdir()
Path('app/config.ini').write_text('debug=1')
open('config.ini').read()
FileNotFoundError: [Errno 2] No such file or directory: 'config.ini'
Anchored path
from pathlib import Path
Path('app').mkdir()
Path('app/config.ini').write_text('debug=1')
base = Path('app')
(base / 'config.ini').read_text()
'debug=1'
3. Backslashes in a normal string
In 'C:\new\table.csv' the \n and \t are escape sequences — the path contains a newline and a tab, so no such file exists. Use a raw string or forward slashes.
Escapes
path = 'C:\new\table.csv'
('\n' in path, '\t' in path)
(True, True)
Raw string
path = r'C:\new\table.csv'
('\n' in path, '\t' in path)
(False, False)

When to use

Use it
  • Optional files: catch it and fall back to defaults
  • Raising it from your own loader when a required path is missing
  • Distinguishing "not there" from "not allowed" (PermissionError)
Reach for something else
  • Checking existence only → Path.exists() / os.path.exists()
  • Deleting a maybe-missing file → Path.unlink(missing_ok=True)
  • Creating folders → Path.mkdir(parents=True, exist_ok=True) before writing

Notes

CPython impl
Objects/exceptions.c — OSError(ENOENT, …) returns FileNotFoundError via the errno map
Catch via
except OSError catches it along with PermissionError, IsADirectoryError, …
Platforms
open() says [Errno 2] everywhere; os.stat/os.remove on Windows say [WinError 2] The system cannot find the file specified

FAQ

A relative path is resolved against the current working directory, which is where the program was started from — not the folder of the script. Running python src/app.py from the project root makes open("data.csv") look in the project root. Print os.getcwd() and os.path.abspath(path) to see where Python looked, and build paths from Path(__file__).parent.

History

3.3
Added, together with the other OSError subclasses (PEP 3151).