Sub topic 9
Handling Missing Files and Permission Errors
This chapter assumes you can open, read, and write files with open() and the with statement, and that you know how try/except selects an exception by type. It covers which exceptions file operations raise, how to catch the ones you can handle, and how to avoid hiding the ones you can't.
Why file operations fail
Your program does not control the file system. Another process can delete a file between two lines of your code. A user can pass a typo as a path. A directory can be read-only. Because of this, every call that touches a file can fail, and you should decide for each one what the program does when it does.
Python reports these failures as exceptions. Most are subclasses of OSError. Python 3.3 made the old names IOError and EnvironmentError aliases of OSError, so you only need OSError in new code.
The OSError family
Python maps the operating system's error code (errno) to a specific subclass where it can. These are the ones you will meet most often.
| Exception | Typical cause | errno name |
|---|---|---|
| `FileNotFoundError` | The file, or a directory in its path, does not exist | `ENOENT` |
| `PermissionError` | Your user lacks the rights for the operation | `EACCES`, `EPERM` |
| `IsADirectoryError` | You opened a directory as if it were a file | `EISDIR` |
| `NotADirectoryError` | A part of the path that should be a directory is a file | `ENOTDIR` |
| `FileExistsError` | You used mode `"x"` or `mkdir` on something that already exists | `EEXIST` |
Because of this hierarchy, except OSError catches all of them, and a more specific except clause lets you treat them differently.
Catching specific errors
This example catches the two most common failures separately.
try:
with open("missing.txt", encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
print("missing.txt does not exist")
except PermissionError:
print("not allowed to read missing.txt")Python checks except clauses from top to bottom and runs the first one that matches. If you put except OSError first, the specific clauses after it never run. Always list subclasses before their parents.
What a missing file really means
FileNotFoundError does not always mean the file itself is absent. It also appears when a directory earlier in the path is absent. This is a common surprise when writing:
try:
with open("reports/2026/summary.txt", "w", encoding="utf-8") as f:
f.write("done\n")
except FileNotFoundError as err:
print(f"cannot create the file: {err}")Mode "w" creates the file but never creates directories. If reports/2026 does not exist, you get FileNotFoundError even though you are only writing. The fix is to create the directory first, with Path("reports/2026").mkdir(parents=True, exist_ok=True).
Reading the details of an error
An OSError carries attributes that tell you more than the message does.
import errno
try:
with open("report.txt", encoding="utf-8") as f:
text = f.read()
except OSError as err:
print("errno: ", err.errno)
print("message: ", err.strerror)
print("filename:", err.filename)
if err.errno == errno.ENOENT:
print("The file or a parent directory is missing.")
elif err.errno == errno.EACCES:
print("Permission denied.")
else:
raiseHere errno.ENOENT and errno.EACCES are named constants for the operating system's numeric codes. The final raise with no argument re-raises the original exception. Use it for any error you did not plan for, so you do not swallow it.
Checking errno is useful for rare codes that have no subclass, such as ENOSPC (disk full) or EROFS (read-only file system). For the common cases, prefer the named subclasses because they are easier to read.
Look before you leap, or try and recover
You can test for a file before opening it:
from pathlib import Path
path = Path("settings.json")
if path.exists():
text = path.read_text(encoding="utf-8")
else:
text = "{}"This looks reasonable but has a race condition. Between exists() and read_text(), another process can delete the file, and your code still raises FileNotFoundError. The check also says nothing about permissions or about whether the path is a directory.
The reliable approach is to attempt the operation and handle the failure:
from pathlib import Path
def read_optional(path, default=""):
try:
return Path(path).read_text(encoding="utf-8")
except FileNotFoundError:
return default
print(repr(read_optional("settings.json", default="{}")))Python programmers call this style "easier to ask forgiveness than permission". It is correct because the operation and its error check are one step. Use exists() when you only want to report something to the user and a wrong answer costs nothing.
Using "x" mode to avoid overwriting
Mode "w" silently truncates an existing file. When you need to create a file only if it is new, use "x", which raises FileExistsError if the path is taken.
try:
with open("lock.txt", "x", encoding="utf-8") as f:
f.write("locked\n")
print("created the lock")
except FileExistsError:
print("lock.txt already exists; someone else holds the lock")The existence check and the creation happen as one operation inside the operating system, so two programs cannot both succeed. This makes "x" a simple tool for lock files and for refusing to overwrite results.
Other failures that look similar
Some problems depend on the platform or are not OSError at all.
- Opening a directory. On Linux and macOS this raises
IsADirectoryError. On Windows it usually raisesPermissionError. If your code must run on both, catchOSErrorand checkPath.is_dir()afterwards, or handle both exceptions. - A file in use. On Windows, deleting or replacing a file that another program holds open raises
PermissionError. On Linux the same operation usually succeeds. - A bad path component.
open("notes.txt/data", encoding="utf-8")raisesNotADirectoryErrorbecausenotes.txtis a file. - Decoding failures. If a file's bytes are not valid in the encoding you chose, reading raises
UnicodeDecodeError. This is a subclass ofValueError, notOSError, soexcept OSErrorwill not catch it.
try:
with open("legacy.txt", encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
text = ""
except UnicodeDecodeError as err:
print(f"not valid UTF-8 at byte {err.start}")
with open("legacy.txt", encoding="utf-8", errors="replace") as f:
text = f.read()With errors="replace", undecodable bytes become the character \ufffd instead of raising. That avoids the crash but loses information, so use it for display and logs, not for data you plan to write back.
Where to put the try block
Keep the try block as small as the operation that can fail. A large block makes it hard to know which line raised and can hide bugs.
import json
class ConfigError(Exception):
"""Raised when the configuration cannot be loaded."""
def load_config(path):
try:
with open(path, encoding="utf-8") as f:
raw = f.read()
except FileNotFoundError as err:
raise ConfigError(f"config file not found: {path}") from err
except PermissionError as err:
raise ConfigError(f"no permission to read: {path}") from err
try:
return json.loads(raw)
except json.JSONDecodeError as err:
raise ConfigError(f"config is not valid JSON: {path}") from errThis function has two separate try blocks, one for the file system and one for parsing. Each failure becomes a ConfigError with a message that names the path. The from err part keeps the original exception attached as the cause, so the traceback still shows what really happened.
Callers now handle one exception type and do not need to know that the config lives in a file.
Choosing a response
Catching an error is only half the job. Decide what the program does next.
| Situation | Reasonable response |
|---|---|
| Optional file such as a user preferences file | Use a default value |
| Required input file named by the user | Print a clear message and exit with a non-zero status |
| Output directory missing | Create it with `mkdir(parents=True, exist_ok=True)`, then retry once |
| File locked by another program (Windows) | Wait briefly and retry a limited number of times |
| Unexpected `OSError` (disk full, I/O error) | Let it propagate, or log it and re-raise |
Retrying makes sense only for temporary conditions. Retrying a FileNotFoundError for a file the user mistyped will never succeed.
Exercise
Why does open("out/result.txt", "w") raise FileNotFoundError when the file does not exist yet, and how do you fix it?
Show answer
Mode "w" creates the file but not missing directories. If the out directory does not exist, the path cannot be resolved, so Python raises FileNotFoundError. Create the directory first with Path("out").mkdir(parents=True, exist_ok=True) and then open the file.
Exercise
Write a function safe_line_count(path) that returns the number of lines in a UTF-8 text file, returns 0 if the file does not exist, and raises RuntimeError("cannot read <path>") if you lack permission. Why is catching FileNotFoundError better than calling Path(path).exists() first?
Show answer
def safelinecount(path): try: with open(path, encoding="utf-8") as f: return sum(1 for _ in f) except FileNotFoundError: return 0 except PermissionError as err: raise RuntimeError(f"cannot read {path}") from err Calling exists() first leaves a gap in which another process can delete the file, so the open can still fail. The try/except makes the check and the open a single operation, and it also covers permission errors that exists() never reports.