Course contents 09 / 22

09 / 22 · Data Structures

Files and exceptions

How Python reports and handles errors and reads and writes files: raise, try, except, else and finally, the exception hierarchy, EAFP against LBYL, exception groups with except* and notes, context managers and the with statement, text and binary files, encodings, pathlib, CSV and JSON.

On this page 11

The previous note produced its data inside the program. Real data lives in files, and reading a file brings two things that the earlier notes could set aside. Operations fail for reasons outside the program’s control: the file is missing, the disk is full, a line holds 1,5 where a number was expected. And some objects hold a resource, an open file, a lock, a network connection, that must be released however the code that uses it ends. Python answers the first with exceptions and the second with context managers and the with statement. This note covers both and then files themselves: text against bytes, encodings, paths, reading a large file without loading it, and the two formats every data project meets, CSV and JSON.

Baseline: error codes#

A function can report failure through its return value, as C functions return −1-1. Python’s str.find works this way: it returns the position of a substring, or −1-1 if there is none. Nothing forces the caller to check:

>>> s = 'abc'
>>> s.find('z')
-1
>>> s[s.find('z')]
'c'
>>> s.index('z')
Traceback (most recent call last):
  ...
ValueError: substring not found

The −1-1 was used as an index, and since negative indices count from the end, the program silently read the last character. Every call that can fail needs an if after it, and a forgotten one turns an error into a wrong answer far from its cause. str.index does the same search and raises an exception instead: the program cannot continue as if the search had succeeded.

Raising and handling exceptions#

The rule (Python language reference, §8.4):

try:
    body
except SomeError as err:     # any number of except clauses, tested in order
    handler
else:                        # optional: runs if the body raised nothing
    no_error
finally:                     # optional: runs on every way out
    cleanup
  1. The body runs. If it raises nothing, else runs, then finally.
  2. If it raises an exception e, the except clauses are tested in order, and the first whose class matches, isinstance(e, SomeError), runs with err bound to e. After the handler, finally runs, and execution continues after the statement.
  3. If no clause matches, finally runs and the exception continues to the caller.
  4. finally also runs when the body or a handler leaves through return, break or continue.

The name err is deleted at the end of its clause; keep the object by assigning it to another name. The order of the blocks shows in a small parser:

>>> def parse(text):
...     try:
...         value = int(text)
...     except ValueError as err:
...         print('except:', err)
...         return None
...     else:
...         print('else: parsed', value)
...         return value
...     finally:
...         print('finally')
...
>>> parse('42')
else: parsed 42
finally
42
>>> parse('4x2')
except: invalid literal for int() with base 10: '4x2'
finally

finally ran after return value had been evaluated and before the function actually returned; the REPL printed 42 last. The else block keeps the try body to the single line that may fail, so that an unexpected ValueError from the code in else is not mistaken for a bad number. Two changes in Python 3.14: except TimeoutError, ConnectionError: may now list several classes without parentheses when there is no as (PEP 758), and a return, break or continue that leaves a finally block draws a SyntaxWarning, because it silently discards any exception in flight (PEP 765).

Raising. raise SomeError('message') raises a new exception, and a bare raise inside a handler re-raises the one being handled. An exception raised while another is being handled remembers it, and raise New(...) from err records the first as the explicit cause; the traceback then shows both (PEP 3134):

>>> def load(cfg, key):
...     try:
...         return cfg[key]
...     except KeyError as err:
...         raise RuntimeError(f'missing setting {key!r}') from err
...
>>> load({}, 'lr')
Traceback (most recent call last):
  ...
KeyError: 'lr'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  ...
RuntimeError: missing setting 'lr'

Why the stack unwinds. Each function call has a frame on the call stack (functions note). When an exception is raised, CPython looks for a handler in the current frame, using a table that the compiler builds for each function from its try blocks; if there is none, the frame is discarded and the search continues in the caller. The traceback is the list of frames passed through, which is why it reads from the outermost call down to the line that raised (running-python note). Since Python 3.11 a try block costs nothing when no exception is raised: the handler table is consulted only when one is (What’s New in Python 3.11).

The exception hierarchy#

The rule. Exceptions are classes in a single hierarchy rooted at BaseException, and except C catches instances of C and of all its subclasses. Programs catch Exception and its descendants. A few classes derive from BaseException directly so that a broad except Exception lets them through (Python documentation, exception hierarchy).

Figure

The built-in exception hierarchy (part)

A tree of exception classesBaseException at the top. Below it SystemExit, KeyboardInterrupt, GeneratorExit, BaseExceptionGroup and Exception. Below Exception, five columns: ArithmeticError with ZeroDivisionError; LookupError with IndexError and KeyError; OSError with FileNotFoundError and PermissionError; ValueError with UnicodeError and UnicodeDecodeError; and TypeError, AttributeError, StopIteration, RuntimeError, ExceptionGroup.BaseExceptionSystemExitKeyboardInterruptGeneratorExitBaseExceptionGroupExceptiondo not catch these in ordinary codeexcept Exception catches all belowArithmeticErrorZeroDivisionErrorLookupErrorIndexErrorKeyErrorOSErrorFileNotFoundErrorPermissionErrorValueErrorUnicodeErrorUnicodeDecodeErrorTypeErrorAttributeErrorStopIterationRuntimeErrorExceptionGroupA tree of exception classesAn indented tree: BaseException; under it SystemExit, KeyboardInterrupt, GeneratorExit, BaseExceptionGroup and Exception; under Exception the categories ArithmeticError, LookupError, OSError and ValueError with their subclasses, and the classes TypeError, AttributeError, StopIteration, RuntimeError, ExceptionGroup.BaseExceptionSystemExitKeyboardInterruptGeneratorExitBaseExceptionGroupExceptionArithmeticErrorZeroDivisionErrorLookupErrorIndexErrorKeyErrorOSErrorFileNotFoundErrorPermissionErrorValueErrorUnicodeErrorUnicodeDecodeErrorTypeErrorAttributeErrorStopIterationRuntimeErrorExceptionGroupdo not catch these in ordinary code
Part of the built-in exception hierarchy of Python 3.14. except C catches exceptions of class C and of every class below it: except LookupError catches both IndexError and KeyError, and except OSError catches FileNotFoundError and PermissionError. The red classes derive from BaseException directly, not from Exception, so except Exception does not intercept them: Ctrl-C (KeyboardInterrupt) and sys.exit() (SystemExit) must be able to stop the program. ExceptionGroup derives from both Exception and BaseExceptionGroup. Amber marks the category classes that are convenient to catch as a whole.
>>> issubclass(KeyError, LookupError), issubclass(FileNotFoundError, OSError)
(True, True)
>>> issubclass(KeyboardInterrupt, Exception), issubclass(ExceptionGroup, Exception)
(False, True)
>>> try:
...     open('no-such-file.txt')
... except OSError as e:
...     print(type(e).__name__, e.errno, e.strerror, e.filename)
...
FileNotFoundError 2 No such file or directory no-such-file.txt

except OSError caught a FileNotFoundError, whose attributes carry the error number and message that the operating system returned for the failed open system call, ENOENT (2), as in the system calls note. The categories in amber are handy to catch whole: LookupError for any failed [], OSError for any failure of the operating system, ValueError for a value of the right type and the wrong content.

The mistakes. A bare except: or except BaseException: catches KeyboardInterrupt too, so the program ignores Ctrl-C; it also catches the SystemExit of sys.exit(). except Exception: around a large block hides bugs, a NameError from a typo or a TypeError from a wrong argument, behind the handling meant for one expected failure. Catch the narrowest class that describes the failure you expect, around the fewest lines that can raise it. A library defines its own exceptions as subclasses of Exception, class ConfigError(Exception): pass, so that callers can catch its errors and only its errors.

EAFP against LBYL#

There are two ways to handle an operation that may fail. LBYL, “look before you leap”, checks first: if key in d: use(d[key]). EAFP, “easier to ask forgiveness than permission”, tries and handles the failure: try: use(d[key]) with except KeyError. Python’s style leans to EAFP (Python glossary), for two reasons.

The check can be stale. For anything outside the program, the state can change between the check and the use. if path.exists(): open(path) can still fail: another process may delete the file in between, a time-of-check to time-of-use race. For files, only EAFP is correct; the open must be inside a try, and the check adds nothing.

The cost depends on how often it fails. Measured on this machine (CPython 3.14.7, Apple M1), per call to a small function that looks a key up in a one-key dict:

key presentkey missing
LBYL: if k in d: return d[k]52 ns43 ns
EAFP: try: return d[k] / except KeyError44 ns130 ns
d.get(k, 0)50 ns49 ns

The try is free when nothing is raised, as the previous section said, so EAFP wins when failure is rare. Raising and catching an exception costs about 90 ns more, so for a lookup that fails often a check or dict.get is cheaper. For dictionaries get, setdefault and defaultdict (dicts note) usually make the question moot.

Exception groups and notes#

Exception groups. Sometimes several unrelated errors happen at once: three of ten parallel downloads fail, or a validation finds two problems in one record. Raising only the first loses the others. Python 3.11 added ExceptionGroup, an exception that carries a list of exceptions, and except*, which handles the members of a group by type (PEP 654):

>>> def check(row):
...     errors = []
...     if row.get('age', 0) < 0:
...         errors.append(ValueError('age must be non-negative'))
...     if 'name' not in row:
...         errors.append(KeyError('name'))
...     if errors:
...         raise ExceptionGroup('invalid row', errors)
...
>>> try:
...     check({'age': -3})
... except* ValueError as eg:
...     print('values:', eg.exceptions)
... except* KeyError as eg:
...     print('keys:', eg.exceptions)
...
values: (ValueError('age must be non-negative'),)
keys: (KeyError('name'),)

The rule. Each except* C clause receives the subgroup of members that match C, as an exception group, and the clauses run one after another, so more than one can run for a single raise, unlike except. Members that no clause matches are re-raised together as a group. Unhandled, a group prints as a tree:

>>> check({'age': -3})
  + Exception Group Traceback (most recent call last):
  |   ...
  | ExceptionGroup: invalid row (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | ValueError: age must be non-negative
    +---------------- 2 ----------------
    | KeyError: 'name'
    +------------------------------------

asyncio.TaskGroup, which runs tasks concurrently, raises an ExceptionGroup of the tasks that failed (concurrency note).

Notes. An exception raised deep inside a library often lacks the context that would explain it: which file, which line, which setting. Since 3.11, err.add_note(text) attaches a string that the traceback prints after the message, without changing the exception’s type (PEP 678):

>>> try:
...     float('1,5')
... except ValueError as err:
...     err.add_note('line 7 of prices.csv')
...     raise
...
Traceback (most recent call last):
  ...
ValueError: could not convert string to float: '1,5'
line 7 of prices.csv

The standard library uses notes itself: in Python 3.14, json.dumps({'tags': {'a', 'b'}}) raises TypeError: Object of type set is not JSON serializable with the note when serializing dict item 'tags', which points to the culprit inside a large structure.

Context managers and with#

A file must be closed, a lock released, a temporary directory deleted, and the release must happen even when the code in between raises. try/finally can do it, but the clean-up then belongs to every caller. A context manager packages the set-up and the clean-up in one object, and the with statement applies it.

The rule. with expr as name: body evaluates expr to a context manager m, calls m.__enter__() and binds its result to name, runs the body, and then calls m.__exit__(exc_type, exc, tb) however the body ended, with the exception’s type, value and traceback or with three Nones. If __exit__ returns a true value, an exception from the body is suppressed; otherwise it continues (PEP 343; the special methods are looked up on the type, as the data model note explains). A class that prints its calls shows the order:

>>> class Timer:
...     def __enter__(self):
...         print('enter')
...         return self
...     def __exit__(self, exc_type, exc, tb):
...         print('exit, exception:', exc_type)
...         return False
...
>>> with Timer() as t:
...     print('body')
...
enter
body
exit, exception: None
>>> with Timer():
...     1 / 0
...
enter
exit, exception: <class 'ZeroDivisionError'>
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero
Figure

What a with statement does

The __enter__ and __exit__ calls of a with blockTwo vertical lines: the with statement and the context manager. The with statement calls Timer() and gets the manager, calls __enter__ and binds self to t. The body raises ZeroDivisionError. Then with calls __exit__ with the exception type; __exit__ returns False, and the exception goes on.with statementcontext managerTimer()manager mm.__enter__()self, bound to tm.__exit__(type, exc, tb)Falsefinds __enter__ and __exit__print('enter'); return selfbody: 1 / 0 raisesZeroDivisionErrortype = ZeroDivisionErrorFalse: the exception goes onTrue would suppress it12345The __enter__ and __exit__ calls of a with blockTwo vertical lines: the with statement and the context manager. The with statement calls Timer() and gets the manager, calls __enter__ and binds self to t. The body raises ZeroDivisionError. Then with calls __exit__ with the exception type; __exit__ returns False, and the exception goes on.with statementcontext managerTimer()manager mm.__enter__()self, bound to tm.__exit__(type, exc, tb)Falsefinds __enter__ and __exit__print('enter'); return selfbody: 1 / 0 raisesZeroDivisionErrortype = ZeroDivisionErrorFalse: the exception goes onTrue would suppress it12345
The block with Timer() as t: 1 / 0 with the Timer class of the text, CPython 3.14.7; time runs downwards. The with statement evaluates its expression to get a context manager (1), calls its __enter__ and binds the result to t (2), and runs the body (3). However the body ends, normally, through return or break, or with an exception, __exit__ is called with the type, value and traceback of the exception, or with three Nones (4). If __exit__ returns a true value the exception is suppressed; here it returned False, and the ZeroDivisionError propagates (5). The REPL printed enter, then the line from __exit__, then the traceback.
  1. Timer() is evaluated, and its type is checked for __enter__ and __exit__.
  2. __enter__ runs and returns the object itself, which is bound to t. A file’s __enter__ also returns the file, which is why with open(p) as f works.
  3. The body raises ZeroDivisionError.
  4. Before the exception leaves the block, __exit__ is called with it.
  5. __exit__ returns False, so the exception propagates, and the traceback appears after the line printed by __exit__.

Context managers from generators. contextlib.contextmanager turns a generator function with a single yield into a context manager: the code before the yield is the set-up, the yielded value is bound by as, and a finally around the yield is the clean-up. It is the generator protocol put to another use:

>>> from contextlib import contextmanager, suppress
>>> @contextmanager
... def tag(name):
...     print(f'<{name}>')
...     try:
...         yield name
...     finally:
...         print(f'</{name}>')
...
>>> with tag('p') as n:
...     print('inside', n)
...
<p>
inside p
</p>
>>> with suppress(FileNotFoundError):
...     open('missing.txt')
...
>>> print('carried on')
carried on

contextlib.suppress is a context manager whose __exit__ returns true for the listed exceptions. Other common ones: open files, threading.Lock, tempfile.TemporaryDirectory, torch.no_grad() in PyTorch, which turns gradient recording off inside its block and back on at its end.

Files: text and bytes#

The rule. open(path, mode='r', encoding=None, newline=None) returns a file object. The mode is a combination of r (read, the default), w (write, truncating the file first), a (append), x (create, failing if the file exists), + (read and write), and t (text, the default) or b (binary). A text file reads and writes str, decoding and encoding with encoding; a binary file reads and writes bytes unchanged (Python documentation, open).

>>> from pathlib import Path
>>> p = Path('notes.txt')
>>> with open(p, 'w', encoding='utf-8') as f:
...     f.write('naïve café\n')
...     f.write('second line\n')
...
11
12
>>> p.read_bytes()
b'na\xc3\xafve caf\xc3\xa9\nsecond line\n'
>>> with open(p, encoding='utf-8') as f:
...     for line in f:
...         print(repr(line))
...
'naïve café\n'
'second line\n'

write returned the number of characters written, 11 for the first line, but the file holds bytes: ï and é take two bytes each in UTF-8, so the first line is 13 bytes on disk. Reading in text mode decoded them back, and iterating over the file gave one line at a time, each with its \n.

Encodings. The bytes mean nothing without the encoding that produced them, as the strings note showed. Read with the wrong one, the same file is either garbled or refused:

>>> with open(p, encoding='latin-1') as f:
...     print(f.read())
...
naïve café
second line

>>> with open(p, encoding='ascii') as f:
...     f.read()
...
Traceback (most recent call last):
  ...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2: ordinal not in range(128)

The mistake is to leave encoding out. Python 3.14 then uses the locale’s encoding, locale.getencoding(), which is UTF-8 on most macOS and Linux systems and often a legacy code page such as cp1252 on Windows, so the same script reads the same file differently on two machines. Always pass encoding='utf-8' for text files; python -X warn_default_encoding makes Python warn wherever it is missing (PEP 597). Python 3.15, released in October 2026, makes UTF-8 the default everywhere (PEP 686). Binary mode is for files that are not text: images, archives, NumPy’s .npy files, model weights.

Line endings. In text mode, newline=None (the default) turns \r\n and \r into \n when reading, and writes \n as the platform’s line ending. The csv module handles line endings itself and asks for newline=''.

What an open file is. A text file object is three objects stacked, and each layer does one job:

Figure

The layers of an open text file

The stack of I/O objects from your code to the kernelFive boxes from top to bottom: your code, TextIOWrapper, BufferedReader, FileIO, the kernel. Between neighbouring boxes an arrow points up: strings from TextIOWrapper to the code, bytes between the other layers.your codefor line in f: … f.read()receives strio.TextIOWrapper (this is f)decodes bytes to str with the encodingturns '\r\n' into '\n'strio.BufferedReader (f.buffer)a 128 KiB buffer: one large readserves many small requestsbytesio.FileIO (f.buffer.raw)file descriptor 3;every read is a system callbytesthe kernelread(2): page cache, then diskbytesThe stack of I/O objects from your code to the kernelFive boxes from top to bottom: your code, TextIOWrapper, BufferedReader, FileIO, the kernel. Between neighbouring boxes an arrow points up: strings from TextIOWrapper to the code, bytes between the other layers.your codefor line in f: … f.read()receives strio.TextIOWrapper (this is f)decodes bytes to str with the encodingturns '\r\n' into '\n'strio.BufferedReader (f.buffer)a 128 KiB buffer: one large readserves many small requestsbytesio.FileIO (f.buffer.raw)file descriptor 3;every read is a system callbytesthe kernelread(2): page cache, then diskbytes
What open('notes.txt', encoding='utf-8') returns in CPython 3.14.7: three objects stacked. The text layer, TextIOWrapper, is f itself; it decodes bytes into strings and translates line endings. Below it a BufferedReader with a buffer of io.DEFAULT_BUFFER_SIZE = 131072 bytes on this build, then a FileIO, which holds the file descriptor and makes the read system calls. In binary mode, open(p, 'rb'), there is no text layer, and f is the BufferedReader itself. What the kernel does next is the subject of the files note in the architecture and operating systems course.
>>> f = open('notes.txt', encoding='utf-8')
>>> f
<_io.TextIOWrapper name='notes.txt' mode='r' encoding='utf-8'>
>>> type(f.buffer).__name__, type(f.buffer.raw).__name__, f.fileno()
('BufferedReader', 'FileIO', 3)
>>> import io
>>> io.DEFAULT_BUFFER_SIZE
131072
>>> f.close()
>>> f.read()
Traceback (most recent call last):
  ...
ValueError: I/O operation on closed file.

The FileIO at the bottom holds the operating system’s file descriptor, 3 here, since 0, 1 and 2 are the standard streams, and each of its reads is a read system call. The BufferedReader above it asks for large blocks and hands them out in small pieces, so that reading a file line by line does not cost one system call per line: the buffering of the files and I/O note, done for you. Writes are buffered the same way, so data written to a file may sit in memory until the buffer fills, f.flush() is called or the file is closed. That is the practical reason for with open(...): __exit__ closes the file, which flushes the buffer and releases the descriptor, even when the body fails. A file that is never closed may lose its last writes, and a process that opens thousands of files without closing them runs out of descriptors.

Reading large files lazily#

The rule. f.read() returns the whole file as one string; f.readlines() returns a list of all lines. Iterating over the file, for line in f, returns one line at a time and reads the next block only when the buffer runs out: a file object is an iterator over its lines.

Figure

Reading a file whole or line by line

Peak memory against file sizeThe red line for f.read() rises straight from 2 MB for a 1 MB file to 32 MB for 16 MB. The blue line for reading line by line lies near zero, about 0.15 MB.081624320481216file size, MBpeak memory, MBf.read(): about 2 × the file sizefor line in f: about 0.15 MB at any sizePeak memory against file sizeThe red line for f.read() rises straight from 2 MB for a 1 MB file to 32 MB for 16 MB. The blue line for reading line by line lies near zero, about 0.15 MB.081624320481216file size, MBpeak memory, MBf.read(): ≈ 2 × file sizefor line in f: ≈ 0.15 MB
The peak memory while reading a text file of 100-byte lines; tracemalloc, CPython 3.14.7 on macOS (arm64), measured once. f.read() holds the bytes it read and the decoded string at the same time, so its peak is about twice the file size: 32 MB for a 16 MB file. The loop for line in f holds the buffer and one line, about 0.15 MB at any file size, and can process a file larger than memory.

f.read() on a 16 MB file peaked at 32 MB, the bytes read and the decoded string held at the same time; iterating line by line stayed at 0.15 MB, mostly the 128 KiB buffer, for every size. A loop over the lines processes a file larger than memory, and it can stop early, after the header or at the first match, without reading the rest. Combined with the generator pipelines of the previous note, it is how large logs and corpora are cleaned, filtered and batched.

Paths#

pathlib.Path represents a path as an object rather than a string (Python documentation, pathlib). The / operator joins parts with the right separator for the system, and the parts of a name are attributes:

>>> from pathlib import Path
>>> p = Path('data') / 'train' / 'prices.csv'
>>> p, p.name, p.stem, p.suffix, p.parent
(PosixPath('data/train/prices.csv'), 'prices.csv', 'prices', '.csv', PosixPath('data/train'))
>>> p.exists()
False
>>> Path('data/train').mkdir(parents=True, exist_ok=True)
>>> p.write_text('day,price\nmon,9.5\ntue,10.25\n', encoding='utf-8')
28
>>> sorted(q.name for q in Path('data').rglob('*.csv'))
['prices.csv']

read_text and write_text open, read or write, and close in one call; glob and rglob find files by pattern, the second in all subdirectories. Python 3.14 adds Path.copy, Path.move and their _into variants for copying and moving files and whole directory trees. Relative paths such as data/train are resolved against the current working directory, the directory the program was started from, not the directory of the script; a script that must find its own data files builds paths from Path(__file__).parent.

CSV and JSON#

CSV. A comma-separated file is text with one record per line. Splitting lines on commas breaks as soon as a field contains a comma inside quotes; the csv module parses the quoting rules (Python documentation, csv). csv.DictReader returns one dict per row, keyed by the header:

>>> import csv
>>> with open('data/train/prices.csv', newline='', encoding='utf-8') as f:
...     rows = list(csv.DictReader(f))
...
>>> rows
[{'day': 'mon', 'price': '9.5'}, {'day': 'tue', 'price': '10.25'}]
>>> sum(float(r['price']) for r in rows)
19.75

Every field comes back as a string, '9.5', and must be converted; a value that does not convert raises ValueError, which is where add_note with the line number earns its keep. For tables of any size the pandas note reads CSV with pd.read_csv, which infers types.

JSON. JSON is a text format for nested data with six kinds of value, which map to Python types: objects to dict, arrays to list, strings to str, numbers to int or float, true and false to bool, and null to None (Python documentation, json). json.dumps and json.loads convert to and from strings, json.dump and json.load to and from files:

>>> import json
>>> config = {'lr': 0.001, 'layers': [64, 32], 'name': 'mlp', 'dropout': None}
>>> text = json.dumps(config)
>>> text
'{"lr": 0.001, "layers": [64, 32], "name": "mlp", "dropout": null}'
>>> json.loads(text) == config
True
>>> json.loads("{'a': 1}")
Traceback (most recent call last):
  ...
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

JSON is not Python syntax: strings need double quotes, and None is null. Tuples come back as lists, keys always as strings, and sets, dates and NumPy arrays are not serializable without a conversion. Experiment configurations, tokenizer vocabularies and the metadata of model checkpoints are commonly stored as JSON; the weights themselves go in binary formats.

What changed#

Error codes and manual clean-up (the baseline)Exceptions, with and file objects
Reporting a failurea special return value, easy to ignorean exception that stops the normal flow
Handling itan if after every callone try at the level that can decide, with except by class
Several failures at onceonly the first is reportedan ExceptionGroup, handled with except*
Releasing a resourceevery caller must rememberwith calls __exit__ on every way out
Reading a filebytes, decoded by handtext mode decodes with an explicit encoding, buffering hidden
A file larger than memorymanual chunked readsfor line in f, constant memory

Limitations#

  • Exceptions are for exceptional cases. Raising and catching costs about 90 ns more than a check on this machine; in an inner loop where failure is common, test first or use dict.get.
  • The buffer is not the disk. Closing a file hands its data to the operating system, which may still hold it in memory; os.fsync forces it to the device, as the files and I/O note explains. Writing a new file and renaming it over the old one is the usual way to avoid a half-written file after a crash.
  • CSV has no standard types. Every field is text, quoting and separators vary between producers, and large tables belong in pandas or in binary formats such as Parquet.
  • Not covered. async with and asynchronous files, mmap for memory-mapped files, shutil for copying trees, pickle (which can execute code while loading and must never be used on untrusted files), and logging, which the debugging note treats.

What you should remember#

  • raise stops the normal flow; the stack unwinds to the first matching except. else runs when nothing was raised, finally on every way out.
  • except C catches C and its subclasses. Catch the narrowest class, around the fewest lines; never a bare except:, which also swallows Ctrl-C.
  • Prefer EAFP for anything outside the program, files above all: the check can be stale. A try that does not raise costs nothing since 3.11.
  • ExceptionGroup and except* handle several errors at once; add_note adds context to an error without changing its type.
  • with calls __enter__, runs the body and then __exit__ however the body ends; contextlib.contextmanager builds a context manager from a generator.
  • A text file is a TextIOWrapper over a BufferedReader over a FileIO over a file descriptor. Always pass encoding='utf-8'; open with with; iterate over lines to read a large file in constant memory.
  • Use pathlib for paths, csv with newline='' for CSV, and json for nested data; values from CSV are strings.

Code#

The script checks the note’s claims in order: a return code against an exception, the blocks of try that run, an exception group handled with except*, a context manager class and one built from a generator, text against bytes and the wrong encoding, a missing file and a note on an error, CSV and JSON round trips, and the peak memory of reading a 4 MB file whole against line by line. All files are written into a temporary directory, which is itself a context manager and is deleted at the end. It needs only the standard library and runs in under a second with python -I files.py; byte counts vary slightly between runs and platforms.

"""Exceptions, context managers and files: text, bytes, CSV and JSON (Python 3.14)."""
import csv
import json
import tempfile
import tracemalloc
from contextlib import contextmanager
from pathlib import Path

# 1. Baseline: a return code can be used by mistake; an exception cannot be ignored
s = "abc"
print(s.find("z"), s[s.find("z")])          # -1 silently indexes the last character
try:
    s.index("z")
except ValueError as err:
    print("ValueError:", err)

# 2. try / except / else / finally: which blocks run
def parse(text, log):
    try:
        value = int(text)
    except ValueError:
        log.append("except")
        return None
    else:
        log.append("else")
        return value
    finally:
        log.append("finally")
for text in ("42", "4x2"):
    log = []
    print(repr(text), parse(text, log), log)

# 3. Exception groups: several independent errors at once, handled by type with except*
def check(row):
    errors = []
    if row.get("age", 0) < 0:
        errors.append(ValueError("age must be non-negative"))
    if "name" not in row:
        errors.append(KeyError("name"))
    if errors:
        raise ExceptionGroup("invalid row", errors)
try:
    check({"age": -3})
except* ValueError as eg:
    print("ValueError group:", [str(e) for e in eg.exceptions])
except* KeyError as eg:
    print("KeyError group:", [str(e) for e in eg.exceptions])

# 4. Context managers: __exit__ runs however the block ends
events = []
class Tracked:
    def __enter__(self):
        events.append("enter")
        return self
    def __exit__(self, exc_type, exc, tb):
        events.append(f"exit {exc_type.__name__ if exc_type else None}")
        return False                         # do not suppress
try:
    with Tracked():
        1 / 0
except ZeroDivisionError:
    events.append("caught outside")
@contextmanager
def tag(name):
    events.append(f"<{name}>")
    try:
        yield name
    finally:
        events.append(f"</{name}>")
with tag("p"):
    events.append("body")
print(events)

with tempfile.TemporaryDirectory() as tmp:  # a context manager too: the directory is deleted on exit
    root = Path(tmp)

    # 5. Text against bytes: the encoding turns characters into bytes and back
    p = root / "notes.txt"
    p.write_text("naïve café\n", encoding="utf-8")
    raw = p.read_bytes()
    print(raw, len(raw), "bytes for", len(p.read_text(encoding="utf-8")), "characters")
    print(raw.decode("latin-1").rstrip())    # wrong encoding: no error, wrong text (mojibake)
    try:
        raw.decode("ascii")
    except UnicodeDecodeError as err:
        print("UnicodeDecodeError:", err.reason, "at byte", err.start)

    # 6. EAFP with files, and adding context to an error
    try:
        (root / "missing.json").read_text(encoding="utf-8")
    except FileNotFoundError as err:
        print("FileNotFoundError:", err.errno, err.strerror)
    try:
        float("1,5")
    except ValueError as err:
        err.add_note("line 7 of prices.csv")
        print(err, err.__notes__)

    # 7. CSV and JSON
    data = root / "prices.csv"
    with open(data, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(["day", "price"])
        writer.writerows([["mon", 9.5], ["tue", 10.25]])
    with open(data, newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    print(rows, sum(float(r["price"]) for r in rows))
    config = {"lr": 0.001, "layers": [64, 32], "dropout": None}
    (root / "config.json").write_text(json.dumps(config, indent=2), encoding="utf-8")
    print(json.loads((root / "config.json").read_text(encoding="utf-8")) == config,
          sorted(q.name for q in root.glob("*.*")))

    # 8. Reading a large file whole against line by line: peak memory
    big = root / "big.txt"
    big.write_text(("x" * 99 + "\n") * 40_000, encoding="utf-8")   # 4 MB
    def peak(f):
        tracemalloc.start()
        f()
        p = tracemalloc.get_traced_memory()[1]
        tracemalloc.stop()
        return p
    def whole():
        with open(big, encoding="utf-8") as f:
            return len(f.read())
    def by_line():
        with open(big, encoding="utf-8") as f:
            return sum(1 for _ in f)
    print(f"read(): {peak(whole):,} bytes   for line in f: {peak(by_line):,} bytes")
print("directory removed:", not root.exists())

# Output with CPython 3.14.7 on an Apple M1, macOS (arm64); byte counts vary slightly:
# -1 c
# ValueError: substring not found
# '42' 42 ['else', 'finally']
# '4x2' None ['except', 'finally']
# ValueError group: ['age must be non-negative']
# KeyError group: ["'name'"]
# ['enter', 'exit ZeroDivisionError', 'caught outside', '<p>', 'body', '</p>']
# b'na\xc3\xafve caf\xc3\xa9\n' 13 bytes for 11 characters
# naïve café
# UnicodeDecodeError: ordinal not in range(128) at byte 2
# FileNotFoundError: 2 No such file or directory
# could not convert string to float: '1,5' ['line 7 of prices.csv']
# [{'day': 'mon', 'price': '9.5'}, {'day': 'tue', 'price': '10.25'}] 19.75
# True ['config.json', 'notes.txt', 'prices.csv']
# read(): 8,132,354 bytes   for line in f: 149,400 bytes
# directory removed: True

Next#

The section on data structures ends here: a program can now hold data in lists, tuples, dictionaries and sets, produce it lazily with generators, and read and write it from files without losing errors or resources. Along the way, several objects behaved like built-ins because they implemented a protocol: iterators with __iter__ and __next__, context managers with __enter__ and __exit__, keys with __hash__ and __eq__. The next section writes such objects. The next note introduces classes: how to define a type of your own, where its attributes live, and how one class builds on another.

For data engineering, the next question is how to express an operation over a table and explain every row of its result. The SQL course starts with a small set of order lines. Tables and the first query

References#