HOWTO · Python
How to Handle File-Opening Exceptions in Python
In Python, when the file we want to access does not exist, an exception known as `FileNotFoundError` is raised. This article will guide you to catch the exception and execute the rest of the code.
On this page
When Python cannot find the path passed to open(), it raises FileNotFoundError. Catch that specific error around the opening operation, choose a useful recovery action, and let the rest of the program continue. Use with open(...) so a successfully opened file is closed reliably.
open() File Modes and Return Value
The built-in open() function takes a path and a mode, and returns a file object. It does not load the entire file when it is called; methods such as read() retrieve content afterward. The default mode, r, opens a text file for reading and expects that path to identify an existing file. Use w to create or replace a file, and a to append to one. These write modes can create a missing file, so choose them only when writing is intended. Add b to a mode such as rb when working with bytes instead of decoded text.
A relative path is resolved from the process’s current working directory, which may differ from the directory containing the Python script. If a path fails unexpectedly, check the exact filename, spelling, parent directories, and the program’s working directory. An absolute path avoids that particular dependence, though it still must identify an accessible file.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "notes.txt"
path.write_text("Read this line.", encoding="utf-8")
with path.open(encoding="utf-8") as file:
print(file.read())
Read this line.
Why open() Raises FileNotFoundError
In read mode, opening a path that does not name an existing file raises FileNotFoundError at the call to open(). Python reports the path it attempted to use; a relative path is interpreted from the current working directory. This commonly means the program is running from a different directory than expected, or a filename or directory component is misspelled. The error is raised while opening the file, before a file object is available, so a later read() call is not the cause.
The same error can occur when a parent directory in the supplied path does not exist. Checking whether a path exists first may help with diagnostics, but it does not remove the possibility that the file changes between the check and the open. Handle the result of the opening operation itself when the program needs to recover.
Handle File-Opening Errors with try and except
Put the operation that may fail inside a try suite and name FileNotFoundError in the matching except clause. When it is raised, Python skips the remaining statements in that try suite and runs the matching handler. Execution then continues after the complete try/except statement. If a different exception is raised and no matching handler exists, it propagates to the caller; catching this one error does not solve every file-access problem.
Using with open(...) means the file is closed when its suite ends, including when an error occurs after a successful open. If opening fails, the with suite never begins. Keep the recovery action useful for the surrounding program: for example, report which path was missing, ask the caller for another path, or use a documented fallback. Avoid silently treating missing input as valid data.
Run this example:
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "missing.txt"
try:
with path.open(encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("Input file was not found; continuing without it.")
print("Program continues.")
Input file was not found; continuing without it.
Program continues.
For another file-reading topic, see [Detecting EOF in Python]({{relref “/HowTo/Python/python end of file.en.md”}}).