Skip to content

Module 13 · File Handling — topic 15 of 15

File exceptions

Errors that file operations raise — FileNotFoundError, FileExistsError, PermissionError, IsADirectoryError, UnicodeDecodeError, JSONDecodeError — and how to handle them gracefully.

Beginner 10 min read·Lesson 208 of 306 in Python Programming

Learning objectives

  • Recognise common file-related exceptions
  • Handle decoding problems
  • Write robust file-loading functions

Definition

File operations raise exceptions when something goes wrong: the file is missing, already exists, isn't accessible, is a directory, or contains data that can't be decoded. Most derive from OSError.

Introduction

Files live outside your program: users delete them, other programs lock them, and they arrive in unexpected encodings. Robust programs expect these problems.

Why it matters

Handling file errors well turns crashes into clear messages such as 'settings file is not valid JSON (line 2)', which users and developers can act on.

Detailed explanation

FileNotFoundError: the file or folder doesn't exist. FileExistsError: creating something that already exists (mode "x", os.mkdir).

PermissionError: the operating system denies access. IsADirectoryError / NotADirectoryError: a folder was used where a file was expected or vice versa.

All of these derive from OSError, which also has errno and filename attributes describing the problem.

UnicodeDecodeError (a ValueError) occurs when bytes can't be decoded with the chosen encoding. Options: use the correct encoding, or errors="replace" to substitute � for bad bytes.

Data-format errors are separate: json.JSONDecodeError for invalid JSON, csv.Error for malformed CSV, ValueError when converting fields.

Catch specific exceptions and give helpful messages; let truly unexpected errors propagate.

Checking os.path.exists first doesn't remove the need for try/except, because the file can change between the check and the open.

Syntax

Python
try:
with open(path, encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
print("missing:", path)
except PermissionError:
print("no access:", path)
except UnicodeDecodeError:
print("not UTF-8 text:", path)
  • Most file errors are OSErrors.
  • Decoding errors are separate.
  • Handle each with a clear message.

Code examples

Common OSErrors

Python
import os
os.makedirs("folder", exist_ok=True)
with open("exists.txt", "w", encoding="utf-8") as f:
f.write("x")
actions = [
lambda: open("missing.txt", encoding="utf-8"),
lambda: os.mkdir("folder"),
lambda: open("exists.txt", "x", encoding="utf-8"),
lambda: os.remove("missing.txt"),
]
for action in actions:
try:
action()
except OSError as e:
print(type(e).__name__, isinstance(e, OSError))
Output
FileNotFoundError True
FileExistsError True
FileExistsError True
FileNotFoundError True

Decoding problems

Python
with open("bytes.bin", "wb") as f:
f.write(b"caf\xe9")
try:
with open("bytes.bin", encoding="utf-8") as f:
f.read()
except UnicodeDecodeError as e:
print("UnicodeDecodeError at byte", e.start)
with open("bytes.bin", encoding="utf-8", errors="replace") as f:
print(f.read())
with open("bytes.bin", encoding="latin-1") as f:
print(f.read())
Output
UnicodeDecodeError at byte 3
caf�
café

More examples

A robust configuration loader

Python
import json
def load_config(path):
try:
with open(path, encoding="utf-8") as f:
return json.load(f), "ok"
except FileNotFoundError:
return {}, "missing - using defaults"
except PermissionError:
return {}, "no permission"
except UnicodeDecodeError:
return {}, "not UTF-8 text"
except json.JSONDecodeError as e:
return {}, f"invalid JSON (line {e.lineno})"
with open("good.json", "w", encoding="utf-8") as f:
f.write('{"debug": true}')
with open("bad.json", "w", encoding="utf-8") as f:
f.write('{\n "debug": tru\n}')
with open("binary.json", "wb") as f:
f.write(b"\xff\xfe\x00")
for p in ["good.json", "missing.json", "bad.json", "binary.json"]:
print(p, "->", load_config(p))
Output
good.json -> ({'debug': True}, 'ok')
missing.json -> ({}, 'missing - using defaults')
bad.json -> ({}, 'invalid JSON (line 2)')
binary.json -> ({}, 'not UTF-8 text')

Step-by-step explanation

  • Each failure mode gets its own clear message instead of a traceback.
  • UnicodeDecodeError is caught before JSONDecodeError because both are ValueErrors and need different messages.
  • JSONDecodeError reports the line number of the problem, which helps users fix the file.

Expected output

Running “A robust configuration loader” prints exactly:

TextOutput
good.json -> ({'debug': True}, 'ok')
missing.json -> ({}, 'missing - using defaults')
bad.json -> ({}, 'invalid JSON (line 2)')
binary.json -> ({}, 'not UTF-8 text')

Practical applications

  • Desktop apps that start with defaults when settings are missing or corrupt.
  • Import tools that report which uploaded file has the wrong encoding.

Best practices

  • Catch specific file exceptions with helpful messages.
  • Use the correct encoding, or errors="replace" deliberately.
  • Prefer try/except (EAFP) over existence checks.

Common mistakes

Check-then-open race

Avoid

if os.path.exists(p):
data = open(p).read()

Prefer

try:
with open(p, encoding="utf-8") as f:
data = f.read()
except FileNotFoundError:
data = None

The file can disappear between the check and the open.

Important notes

  • This completes the File Handling module; next comes organising code into modules and packages.

Key takeaways

  • File errors are mostly OSError subclasses.
  • Decoding problems raise UnicodeDecodeError.
  • Handle each failure with a clear message.

Try it yourself

  1. 1
    Write read_lines(path) that returns [] for a missing file and raises a clear error for undecodable files.
  2. 2
    Extend load_config to also catch IsADirectoryError when the path is a folder.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateOpening a missing file for reading raises which exception?
Practise this topic