Sub topic 9
Handling missing files and permission errors
This chapter assumes you can use open() and the with statement, and that you know basic try/except. It shows how to handle the failures that file operations raise most often.
Why file operations fail
A file call depends on things outside your program: the disk, the operating system, and other processes. The code can be correct and still fail because the file is not there or you may not touch it. Python reports these failures as exceptions, so you decide what happens next instead of crashing.
The exception family
Most file failures raise a subclass of OSError. Catching the specific subclass lets you react to one cause at a time.
| Exception | Typical cause |
|---|---|
| `FileNotFoundError` | Reading a file that does not exist, or writing into a folder that does not exist |
| `PermissionError` | The operating system denies read or write access |
| `IsADirectoryError` | You opened a directory as if it were a file |
| `FileExistsError` | Mode `"x"` was used and the file already exists |
Catching specific errors
List the specific exceptions first and put the general OSError last as a fallback. Python uses the first matching except clause, so a general clause placed first would hide the specific ones.
def read_text_or_default(path, default=""):
try:
with open(path, encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
print(f"{path} does not exist, using default")
return default
except PermissionError:
print(f"not allowed to read {path}")
raise
except OSError as err:
print(f"could not read {path}: {err}")
raise
print(repr(read_text_or_default("missing.txt", default="(empty)")))A missing file often has a sensible fallback, such as a default. A permission problem usually does not, so the example reports it and re-raises with a bare raise. This keeps the original traceback and lets the caller decide.
Every OSError carries an errno number and a strerror message, which are useful in logs:
try:
open("/root/secret.txt", encoding="utf-8")
except OSError as err:
print(err.errno, err.strerror, err.filename)Ask forgiveness, not permission
You might be tempted to check first with Path.exists() or os.access() and then open the file. This is unreliable, because the file can be deleted or its permissions changed between the check and the open() call. That gap is a race condition. Python style prefers to try the operation and handle the exception, which is the approach the examples above take.
Common mistakes
- A relative path resolves against the working directory, not the script's folder. A
FileNotFoundErrorfor a file you can see usually means the program started elsewhere. PrintPath.cwd(), or build the path fromPath(__file__).parent. - Writing into a missing folder.
open("out/report.txt", "w")raisesFileNotFoundErrorifoutdoes not exist. Create it first withPath("out").mkdir(parents=True, exist_ok=True). - Using a bare
except:orexcept Exception: pass. This hides real bugs such as typos. Name the exceptions you expect. - Putting too much inside
try. Keep the block small, so an error in your own processing code is not mistaken for a file error. Useelsefor the code that should run only when the file opened. - Expecting
OSErrorto cover decoding problems.UnicodeDecodeErroris aValueError, so it needs its ownexceptclause.
try:
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
except FileNotFoundError:
print("notes.txt does not exist")
except UnicodeDecodeError:
print("notes.txt is not valid UTF-8")
else:
print(f"read {len(text)} characters")Exercise
A script runs open("reports/today.txt", "w") and raises FileNotFoundError, although today.txt has never existed and you expected it to be created. What is the likely cause, and how do you fix it?
Show answer
Write mode creates the file but not its parent folder, so the reports directory is probably missing. Create it first with Path("reports").mkdir(parents=True, exist_ok=True), then open the file.