01A.9 Files, Paths, JSON and CSV

FoundationsLesson 9 of 1112,462 words7 parts
Module 01A · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

Almost everything an AI engineer builds reads from and writes to files: datasets, prompts, eval results, logs, checkpoints, downloaded models, exported reports. Three formats do most of that work — text files you read line by line, JSON (and its line-delimited cousin JSONL) for structured data, and CSV for flat tables — and underneath all of them sits the humble problem of where a file actually is. This lesson teaches the standard-library tools for all of it: pathlib for paths, open() and with for reading and writing, the json module in depth (including JSON Lines), the csv module, and a working tour of the neighbouring formats (tomllib, configparser, pickle, gzip, zipfile) plus the habits that keep file code safe: explicit encodings, atomic writes, idempotent scripts and path-traversal checks. Everything runs on the standard library alone — no installs, no network, no API keys.

What you'll learn

  • How pathlib.Path models filesystem paths — joining, names, resolve(), relative_to(), glob/rglob, mkdir, read_text/write_text — and why relative paths depend on the working directory, not the script
  • How to open, read and write files correctly: modes, encoding="utf-8" always, newline="" for CSV, with blocks, line-by-line and chunked reading for big files, binary mode, io.StringIO/BytesIO, seek/tell
  • How to write files safely: atomic write-then-rename, append-only logs, and what "partial write" and "crash mid-write" mean
  • The json module completely: loads/dumps/load/dump, output-shaping options, default= and parse_float, object_hook, JSONDecodeError forensics, raw_decode for extracting JSON from prose, JSON Lines streaming, and how to validate JSON structure by hand
  • The csv module completely: reader/writer vs DictReader/DictWriter, quoting and dialects, newline="", encodings and the BOM, type conversion and missing values
  • The neighbouring formats — TOML, YAML, INI, pickle, gzip/zip — and when each is the right choice
  • Robust file handling: the real exceptions, path traversal and Path.is_relative_to(), idempotent scripts, --dry-run, and reporting what was skipped
  • Five end-to-end mini-projects, all run for real: a log analyser, a CSV→JSON converter, a JSONL de-duplicator, a folder indexer, and a tiny JSON key-value store

What you don't need

  • Any third-party package. Everything here is the standard library on Python 3.11+. (pyyaml, openpyxl and ijson appear only as labelled awareness notes.)
  • An API key or network access. Every snippet runs offline on deterministic fixture data.
  • Database knowledge. SQLite gets one pointer (00.7); you don't need it for this lesson.

Setup

Python 3.11 or newer (3.13/3.14 recommended — as of November 2026, 3.15 is the newest release and 3.11–3.14 are all still maintained; see 01A.1 for the release-cycle detail). You need only the standard library — no API key needed, nothing to install. Run snippets with any Python 3.11+ interpreter:

bash
python3 script.py          # or: uv run script.py  (uv can install/manage Python for you)

Working-directory note, because it matters in this lesson: the snippets below create small fixture folders (demo09/, json09/, csv09/…) in whatever directory you run them from, so run each one from a scratch folder, not inside a real project.


What you must be able to do after this lesson#

  • Build and inspect paths with pathlib
  • Read and write text files with a with block and utf-8 encoding
  • Read and write JSON with the json module
  • Read and write CSV with DictReader and DictWriter
  • Write a file safely so a crash does not corrupt it
  • Handle missing files and bad input without crashing

Why this matters for an AI engineer#

File I/O looks mundane until it isn't — and in AI work it fails in characteristic ways: a CSV export with a BOM, a 40 GB JSONL eval set, a model response that's almost JSON, a download that must not be trusted. Here's what you'll keep hearing, and where this lesson answers it:

You'll hear... You'll understand it after...
"The script works on my machine but not in CI." 1.1 The working directory vs the script's directory
"Always pass encoding='utf-8' — Windows defaults bite." 2.2 The encoding rule
"Never json.loads a model response bare." 3.3 JSONDecodeError forensics and raw_decode
"Eval sets and batch files are JSONL, one object per line." 3.5 JSON Lines
"That CSV came from Excel — check the BOM and the quoting." 4.3 newline="", encodings and the BOM
"Pickle model files are arbitrary code execution." 5.4 pickle
"Write to a temp file, then os.replace — atomic." 2.5 Writing safely
"Validate the path before you open it." 6.2 Path traversal
"Re-running the job must not duplicate records." 6.3 Idempotent scripts

Part 1: Paths and the filesystem with pathlib#

1.1 The working directory vs the script's directory#

The single most common file bug in Python isn't about files at all — it's about where the program is standing. A relative path like Path("data/tickets.csv") is resolved against the process's current working directory (CWD): wherever you typed the command, not wherever the script lives. Run the same script from two directories and the same relative path finds two different files — or none.

python
# app09/scripts/show_config.py — naive vs __file__-anchored path lookup
from pathlib import Path

naive = Path("data") / "config.txt"                       # relative to the CWD
anchored = Path(__file__).resolve().parent.parent / "data" / "config.txt"

print("naive path exists :", naive.exists())
print("anchored exists   :", anchored.exists())
print("anchored is under app dir:", anchored.is_relative_to(Path(__file__).resolve().parent.parent))

Run from inside app09/ it finds the file both ways; run from the parent directory the naive path fails while the anchored one still works. Output:

text
--- cwd = app dir ---
naive path exists : True
anchored exists   : True
anchored is under app dir: True
--- cwd = scratch root ---
naive path exists : False
anchored exists   : True
anchored is under app dir: True

The old os.path module does all of this too (os.path.join, os.getcwd, os.path.dirname(__file__)), and you'll see it in older code and in third-party libraries. pathlib is the modern, object-oriented spelling and the one this path teaches; the two interoperate freely (os.fspath(path) converts a Path to a string when an old API demands one).

1.2 Path objects: joining, names, parts#

pathlib.Path is a class representing a filesystem path. The / operator joins parts — it works on any OS and never produces data\\raw on Windows or data//raw from a stray slash:

python
# p1_paths.py — pathlib essentials (creates its own demo09/ fixture, safe to re-run)
import shutil
from pathlib import Path

WORK = Path("demo09")
if WORK.exists():
    shutil.rmtree(WORK)
(WORK / "data" / "raw").mkdir(parents=True)
(WORK / "reports").mkdir()
(WORK / "data" / "raw" / "tickets.csv").write_text("id,subject\n1,x\n", encoding="utf-8")
(WORK / "notes.txt").write_text("hello\n", encoding="utf-8")

base = WORK / "data" / "raw" / "tickets.csv"   # / joins path parts
print("joined :", base)
print("name   :", base.name)        # tickets.csv
print("stem   :", base.stem)        # tickets
print("suffix :", base.suffix)      # .csv
print("parent :", base.parent)      # demo09/data/raw
print("parts  :", base.parts)       # ('demo09', 'data', 'raw', 'tickets.csv')
print("exists :", base.exists(), "| is_file:", base.is_file())

print("with_name  :", base.with_name("tickets-2026.csv"))
print("with_suffix:", base.with_suffix(".json"))

# resolve() makes a path absolute and follows symlinks; relative_to() re-anchors it
abs_path = base.resolve()
print("resolve is absolute:", abs_path.is_absolute())
print("back to relative:", abs_path.relative_to(Path.cwd()))

# mkdir(parents=True, exist_ok=True): nested dirs, no error if already there
(WORK / "reports" / "q4").mkdir(parents=True, exist_ok=True)
(WORK / "reports" / "q4").mkdir(parents=True, exist_ok=True)  # second call is fine
print("reports/q4 is_dir:", (WORK / "reports" / "q4").is_dir())

# iterdir / glob / rglob
print("data children:", sorted(p.name for p in (WORK / "data").iterdir()))
print("all .csv under data:", sorted(str(p) for p in (WORK / "data").rglob("*.csv")))
print("top-level .txt:", [p.name for p in WORK.glob("*.txt")])

# home() and cwd() — print only machine-independent facts
print("home() absolute:", Path.home().is_absolute())
Output16 lines
joined : demo09/data/raw/tickets.csv
name   : tickets.csv
stem   : tickets
suffix : .csv
parent : demo09/data/raw
parts  : ('demo09', 'data', 'raw', 'tickets.csv')
exists : True | is_file: True
with_name  : demo09/data/raw/tickets-2026.csv
with_suffix: demo09/data/raw/tickets.json
resolve is absolute: True
back to relative: demo09/data/raw/tickets.csv
reports/q4 is_dir: True
data children: ['raw']
all .csv under data: ['demo09/data/raw/tickets.csv']
top-level .txt: ['notes.txt']
home() absolute: True

The vocabulary worth memorising:

Member Meaning Example on demo09/data/raw/tickets.csv
p / "x" join path parts Path("a") / "b.csv" → a/b.csv
p.name final component, with suffix tickets.csv
p.stem final component, without suffix tickets
p.suffix / p.suffixes last extension / all extensions .csv / ['.csv'] (.tar.gz → ['.tar', '.gz'])
p.parent everything up to the last component demo09/data/raw
p.parts tuple of components ('demo09', 'data', 'raw', 'tickets.csv')
p.with_name(x) / p.with_suffix(x) replace final name / extension tickets-2026.csv, tickets.json
p.resolve() absolute path, symlinks followed, .. collapsed /…/demo09/data/raw/tickets.csv
p.relative_to(base) re-anchor under base; raises ValueError if not inside data/raw/tickets.csv from Path.cwd()
p.is_relative_to(base) boolean version (3.9+) the path-traversal guard in 6.2
p.exists() / is_file() / is_dir() filesystem predicates True / True / False
p.mkdir(parents, exist_ok) create directories parents=True makes intermediates; exist_ok=True won't fail if present
p.iterdir() / p.glob(pat) / p.rglob(pat) list children / match patterns / match recursively rglob("*.csv") finds every CSV below data/
Path.home() / Path.cwd() user's home / process working directory anchors for "where am I?"

Two pattern subtleties: glob/rglob patterns are not regex — * matches within one directory level's name, ** (only meaningful with rglob, or glob("**/*.csv")) crosses directories, ? matches one character, [0-9] matches a character class. And dotfiles are not special to pathlib: iterdir(), glob("*") and rglob("*") all return hidden files — the opposite of the glob module, which skips them unless you pass include_hidden=True (3.11+). Choose iterdir/glob for one directory level and rglob when you want recursion; neither needs a dotfile workaround.

Two related tools worth knowing. The pure-path classes — PurePath (flavour of the OS you're on), PurePosixPath, PureWindowsPath — do all the joining, splitting and comparing with no filesystem access at all, which makes them handy for parsing paths that belong to another OS (a Windows export on your Mac) or for unit-testing path logic without touching disk. And for symlinks specifically: p.is_symlink() tests whether a path is a link, p.readlink() returns its target, and p.symlink_to(target) creates one (privileges permitting) — resolve() is the operation that follows them.

1.3 shutil, tempfile, and the rest of the toolbox#

pathlib covers paths and small reads/writes. For anything that moves, copies or cleans up trees, the standard library's other filesystem modules take over:

  • shutil — high-level file operations: copy, copy2 (preserves metadata), copytree, move, disk_usage, and rmtree (recursive delete). Python 3.14 added Path.copy(), Path.copy_into(), Path.move() and Path.move_into() to pathlib itself (What's New in 3.14, as of November 2026); on 3.11–3.13 shutil is the way, and it still works everywhere.
  • tempfile — secure temporary files and directories: TemporaryDirectory() (auto-deleted on exit), NamedTemporaryFile(), mkstemp() (returns an fd + path), tempfile.gettempdir().
  • os — the low-level layer underneath: os.replace (atomic rename — see 2.5), os.environ, os.walk, os.remove, os.makedirs. You'll meet os constantly; pathlib just spells most of it more readably.
  • glob (the module) and fnmatch — pattern matching when pathlib's built-ins aren't enough.

tempfile exists precisely so you never hand-roll "pick a random name in /tmp":

python
import tempfile
from pathlib import Path

with tempfile.TemporaryDirectory() as td:            # deleted automatically on exit
    scratch = Path(td) / "out.csv"
    scratch.write_text("a,b\n1,2\n", encoding="utf-8")
    print("inside temp dir:", scratch.name, "| exists during with:", scratch.exists())
print("after with-block, dir gone:", not Path(td).exists())
Output2 lines
inside temp dir: out.csv | exists during with: True
after with-block, dir gone: True

Part 2: Reading and writing files properly#

2.1 open() and the modes that matter#

open(path, mode) returns a file object — a stream you read from or write to. The mode string combines a base mode with optional modifiers:

Mode Meaning Creates? Truncates?
"r" read (text) no — FileNotFoundError if missing —
"w" write (text) yes yes — destroys existing content
"a" append (text) yes no — writes go to the end
"x" exclusive create (text) yes fails with FileExistsError if present
"r+", "w+", "a+", "x+" the above plus reading varies varies
"b" anywhere binary mode — bytes not str — —
"t" anywhere text mode (the default) — —
python
# p2_files.py — open() modes, reading strategies, seek/tell, StringIO/BytesIO, atomic write
import io, os, tempfile
from pathlib import Path

WORK = Path("files09"); WORK.mkdir(exist_ok=True)

# --- modes: r w a x + b -------------------------------------------------------
p = WORK / "log.txt"
p.write_text("one\n", encoding="utf-8")          # 'w' creates/truncates
with p.open("a", encoding="utf-8") as f:          # 'a' appends
    f.write("two\n")
print("after append:", p.read_text(encoding="utf-8").splitlines())
try:
    with p.open("x", encoding="utf-8") as f:     # 'x' fails if the file exists
        f.write("three\n")
except FileExistsError as e:
    print("x mode on existing file ->", type(e).__name__)
with p.open("r+", encoding="utf-8") as f:         # r+ : read+write, no truncation
    print("r+ first line:", f.readline().strip())

# --- reading: whole file vs lines vs chunks ------------------------------------
big = WORK / "numbers.txt"
big.write_text("".join(f"{i}\n" for i in range(5)), encoding="utf-8")
print("read() whole   :", repr(big.read_text(encoding="utf-8")))
with big.open(encoding="utf-8") as f:
    print("readline loop  :", [line.strip() for line in f])
with big.open("rb") as f:                          # binary chunked read
    chunks = [c for c in iter(lambda: f.read(7), b"")]
print("7-byte chunks   :", chunks)

# --- seek / tell ----------------------------------------------------------------
with big.open(encoding="utf-8") as f:
    f.seek(2)                                     # ASCII file: offset 2 is the start of line 2 (text-seek caveat: §2.6)
    print("tell after seek(2):", f.tell(), "| rest:", repr(f.read()))

# --- StringIO / BytesIO ----------------------------------------------------------
buf = io.StringIO()
buf.write("name,qty\napple,3\n")
buf.seek(0)
print("StringIO value :", repr(buf.read()))
raw = io.BytesIO(b"\x89PNG\r\n\x1a\n" + b"\x00" * 8)
print("BytesIO len    :", len(raw.getvalue()), "| magic:", raw.getvalue()[:4])

# --- atomic write: temp file + os.replace ---------------------------------------
target = WORK / "report.json"
tmp = tempfile.NamedTemporaryFile("w", dir=WORK, delete=False, encoding="utf-8")
try:
    tmp.write('{"status": "ok", "rows": 41}\n')   # pretend this is a long write
    tmp.close()
    os.replace(tmp.name, target)                  # atomic on POSIX and Windows
finally:
    if os.path.exists(tmp.name):
        os.unlink(tmp.name)
print("atomic result  :", target.read_text(encoding="utf-8").strip())
Output10 lines
after append: ['one', 'two']
x mode on existing file -> FileExistsError
r+ first line: one
read() whole   : '0\n1\n2\n3\n4\n'
readline loop  : ['0', '1', '2', '3', '4']
7-byte chunks   : [b'0\n1\n2\n3', b'\n4\n']
tell after seek(2): 2 | rest: '1\n2\n3\n4\n'
StringIO value : 'name,qty\napple,3\n'
BytesIO len    : 16 | magic: b'\x89PNG'
atomic result  : {"status": "ok", "rows": 41}

Path shortcuts cover the common cases without an explicit open: p.read_text(encoding="utf-8"), p.read_bytes(), p.write_text(text, encoding="utf-8"), p.write_bytes(data). Use open()/p.open() when you need streaming (line-by-line, chunks), append mode, or the with block's explicitness — which is nearly always for anything bigger than a small config file.

2.2 The encoding rule: always encoding="utf-8"#

Text mode translates between str and bytes using an encoding — the table that says which byte sequences mean which characters. If you don't pass encoding=, Python uses locale.getpreferredencoding() — which on Windows is often a legacy code page like cp1252, not UTF-8. A file containing café written as UTF-8 then read as cp1252 becomes café; worse, the write side can fail outright on characters the code page lacks.

The rule this path teaches, everywhere: always pass encoding="utf-8" explicitly on both read and write. UTF-8 is what JSON mandates for interchange (RFC 8259 §8.1), what virtually every export and API uses, and what every OS handles. Python has used UTF-8 by default for open() on every platform since 3.15 (PEP 686 enables UTF-8 mode by default — opt out with PYTHONUTF8=0 or -X utf8=0). On 3.11–3.14 the default is still the locale encoding — usually UTF-8 on macOS/Linux, but often a legacy code page like cp1252 on Windows, and plain ASCII under a POSIX/C locale on any OS — which is exactly why the bug hides until it doesn't. Explicit is correct on every version and every platform.

When the file isn't UTF-8 — legacy exports, Excel CSVs from certain locales — say so: encoding="cp1252", encoding="latin-1" (which never fails: every byte maps to a character). And when you don't know, errors= controls what happens on undecodable bytes: errors="replace" substitutes �, errors="ignore" drops them, errors="surrogateescape" round-trips arbitrary bytes losslessly (useful for log processing). The default, errors="strict", raises UnicodeDecodeError — the right choice for data you intend to trust, because silent corruption is worse than a loud failure.

2.3 with, closing, and the errors you'll actually meet#

A file object holds an operating-system resource. with open(...) as f: guarantees f.close() runs when the block exits — normally or via exception — which is why every explicit open() in this lesson sits inside with (the Path.read_text/write_text/read_bytes/write_bytes shortcuts do the same open-and-close for you). Forgetting it "works" in short scripts (CPython refcounting closes the file when f is garbage-collected) but leaks file descriptors in loops and servers, and on PyPy/Jython it may not close at all. The with statement is 01A.8's context-manager topic applied to the most common resource there is.

The exceptions you'll meet, with the real tracebacks (note how 01A.8 teaches you to read them — the last line is the diagnosis). Paths are elided, so treat these as illustrative:

Example output · illustrative10 lines
Traceback (most recent call last):
  File "...", line 1, in <module>
    open('err09/nope.txt', encoding='utf-8')
FileNotFoundError: [Errno 2] No such file or directory: 'err09/nope.txt'

IsADirectoryError: [Errno 21] Is a directory: 'err09'

PermissionError: [Errno 13] Permission denied: 'err09/ok.txt'

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 3: invalid continuation byte
  • FileNotFoundError — the path doesn't exist (a subclass of OSError). Check p.exists() first if absence is normal; otherwise let it raise — a missing input file is a real error, not a case to swallow.
  • IsADirectoryError — you tried to read a directory as a file. Happens with user-supplied paths; guard with p.is_file().
  • PermissionError — the OS refused: file permissions, a read-only location, or a sandbox. Don't retry blindly; it's a configuration problem.
  • UnicodeDecodeError — bytes that aren't valid in the declared encoding (2.2).

The pattern that covers all of them in production code is catch the specific exception at the boundary, report, continue or fail loudly — 01A.8 owns the full treatment; the CSV→JSON converter in 7.3 shows it per-row.

2.4 Whole file vs line-by-line vs chunks#

Three ways to read, three memory profiles:

Approach Code Memory Use when
Whole file p.read_text() / f.read() entire file + the str small files: configs, JSON docs, prompts
Line by line for line in f: / f.readlines() one line at a time / list of all lines logs, JSONL, CSV, anything row-shaped
Fixed chunks f.read(65536) in a loop, or iter(lambda: f.read(n), b"") bounded binary files, files with no line structure

The line-by-line form is the one that matters for AI work: eval datasets, batch API files and logs are JSONL/CSV precisely so you can stream them — a 10-million-line file processes in constant memory. for line in f on a text file yields lines with the trailing \n; strip it (line.rstrip("\n") or just pass to json.loads, which tolerates trailing whitespace). For binary chunked reads, iter(lambda: f.read(65536), b"") is the idiom — it calls read until it returns the sentinel b"" (empty = EOF).

2.5 Writing safely: atomic writes and append-only logs#

Two production habits separate toy file code from real file code:

Atomic writes. p.write_text(data) truncates the target then writes — a crash mid-write leaves a half-written file that the next run mistakes for good data. The fix: write to a temporary file in the same directory, then os.replace(tmp, target) — a single atomic rename on POSIX and Windows. Readers see either the old complete file or the new complete file, never a torn one. This is the same "write-then-flip" pattern 05.9 uses for ingestion manifests; the key-value store in 7.6 implements it in 15 lines.

One step further: surviving a machine crash. Temp-file-plus-rename protects against a process crash and against readers ever seeing a torn file — but a power loss or kernel panic can still lose data the OS hadn't flushed to stable storage: the rename can "succeed" while the file's contents, or the directory entry recording it, never reach the disk. True durability adds fsync — flush Python's buffer, os.fsync the file descriptor before the rename, then os.fsync the containing directory after it:

python
# the durable version of the pattern — as it appears in save() in §7.6
# (fd/tmp come from tempfile.mkstemp; target is the destination path)
with os.fdopen(fd, "w", encoding="utf-8") as f:
    json.dump(data, f)
    f.write("\n")
    f.flush()
    os.fsync(f.fileno())          # contents on stable storage BEFORE the rename
os.replace(tmp, target)           # atomic rename — now durable as well
dir_fd = os.open(target.parent, os.O_RDONLY)   # POSIX only — Windows can't fsync a directory
try:
    os.fsync(dir_fd)              # the directory entry itself must reach the disk
finally:
    os.close(dir_fd)

Two extra syscalls per write is nothing for a batch job — skip it for throwaway outputs, keep it for anything you'd be sad to lose: ledgers, checkpoints you resume from, the KV store in 7.6 (whose save() shows the file half of this pattern). This is the same reason databases "fsync before commit".

Append-only logs. For logs and event streams, "a" mode appends — but on some network filesystems O_APPEND isn't atomic, so two processes can interleave lines. For multi-process logging use the logging module with RotatingFileHandler (01A.8 covers it); for your own single-writer event files, "a" + one write() per record is fine. Always open log files with encoding="utf-8" and end each record with \n.

File locking (fcntl.flock on POSIX, msvcrt.locking on Windows, or the cross-platform filelock package) is the awareness-level topic here: you need it when multiple processes append to one file or coordinate read-modify-write cycles. Single-process scripts don't need it — say so honestly rather than cargo-culting locks everywhere.

2.6 Binary files, StringIO/BytesIO, seek/tell, line endings#

Binary mode ("rb"/"wb") skips encoding entirely: you get bytes. You need it for images, PDFs, model weights, zip/gzip payloads — anything that isn't text. 03.6 shows why API attachments are bytes→base64; 05.2 opens PDFs as binary streams. The magic-bytes habit — read the first few bytes to identify a file — is p.read_bytes()[:8] or p.open("rb").read(8). A PNG starts b'\x89PNG\r\n\x1a\n'; a PDF starts b'%PDF'; a ZIP starts b'PK\x03\x04'. The str/bytes boundary is strict in both directions: f.write("text") on a "wb" file raises TypeError: a bytes-like object is required, not 'str', and f.write(b"bytes") on a text file raises TypeError: write() argument must be str, not bytes — the mode and the type you pass must match.

io.StringIO / io.BytesIO are in-memory file objects — same interface as real files, no disk. Two uses you'll actually hit: (1) csv.writer needs a file-like object, so io.StringIO lets you render CSV to a string (e.g., to embed in an HTTP response or email) instead of a file; (2) tests — feed a fake file to code that expects open(). BytesIO is the binary twin (base64-encoded payloads, in-memory zip building).

seek/tell move the read/write position: f.seek(0) rewinds to the start (needed before re-reading a StringIO, or after writing before reading in "w+"/"r+" mode), f.tell() reports the current offset, f.seek(n, 2) seeks relative to end. In text mode seek takes an opaque cookie from tell, not necessarily a byte offset on all platforms — for binary it is a byte offset.

Line endings are three conventions: \n (LF, POSIX/macOS), \r\n (CRLF, Windows), \r (CR, classic Mac). Text mode with default newline=None performs universal newline translation: every variant is read as \n, and \n is written as os.linesep. For CSV you must pass newline="" so the csv module sees the raw endings (4.3). For JSONL and most interchange, LF-only is the convention — JSON Lines spec and git both prefer it.


Part 3: JSON in depth#

00.6 already established what JSON is and the basic loads/dumps round trip — including the type-mapping table and the NaN trap. This part goes where AI engineering actually lives: serialising files and API payloads, surviving the round trip, extracting JSON from messy text, and streaming JSON Lines.

3.1 loads/dumps vs load/dump#

Four functions, two pairs:

Function Works on Use when
json.dumps(obj) → str Python object → JSON string building a payload in memory, embedding in a file you write yourself
json.loads(text) → obj JSON string → Python object parsing a response body, a line of JSONL, a config string
json.dump(obj, file) writes JSON into an open file object streaming to disk; pair with indent= for pretty files
json.load(file) reads JSON from an open file object loading a whole .json document
python
# p3_json.py — dumps options, load/dump to files, JSONDecodeError forensics
import json
from pathlib import Path

WORK = Path("json09"); WORK.mkdir(exist_ok=True)

ticket = {"id": 1042, "subject": "Cannot log in", "status": "open",
          "priority": 2, "tags": ["login", "urgent"], "score": 0.875}

# output-shaping options
print(json.dumps(ticket))
print(json.dumps(ticket, indent=2, sort_keys=True))
print(json.dumps(ticket, ensure_ascii=False, separators=(",", ":")))
print(json.dumps({"note": "café — naïve"}, ensure_ascii=False))
print(json.dumps({"note": "café — naïve"}))           # default escapes non-ASCII

# dump/load work on file objects; Path.read_text/write_text are the shortcut
out = WORK / "ticket.json"
with out.open("w", encoding="utf-8") as f:
    json.dump(ticket, f, indent=2, sort_keys=True)
with out.open(encoding="utf-8") as f:
    back = json.load(f)
print("round trip equal:", back == ticket)
print("sorted keys in file:", out.read_text(encoding="utf-8").splitlines()[1].strip())

# JSONDecodeError carries msg/doc/pos/lineno/colno
bad = '{\n  "id": 1,\n  "status": open,\n  "x": 2\n}'
try:
    json.loads(bad)
except json.JSONDecodeError as e:
    print("err:", e.msg, "| line", e.lineno, "col", e.colno, "| pos", e.pos)
Output18 lines
{"id": 1042, "subject": "Cannot log in", "status": "open", "priority": 2, "tags": ["login", "urgent"], "score": 0.875}
{
  "id": 1042,
  "priority": 2,
  "score": 0.875,
  "status": "open",
  "subject": "Cannot log in",
  "tags": [
    "login",
    "urgent"
  ]
}
{"id":1042,"subject":"Cannot log in","status":"open","priority":2,"tags":["login","urgent"],"score":0.875}
{"note": "café — naïve"}
{"note": "caf\u00e9 \u2014 na\u00efve"}
round trip equal: True
sorted keys in file: "id": 1042,
err: Expecting value | line 3 col 13 | pos 25

The output-shaping options, all keyword arguments to dumps/dump:

Argument Effect When you want it
indent=2 pretty-print, one field per line files humans or git diff will read; the default for .json on disk
sort_keys=True alphabetical key order deterministic output — stable diffs, stable hashes, stable tests
ensure_ascii=False emit Unicode literally (café) instead of \u00e9 almost always: readable files, smaller payloads for non-Latin text
separators=(",", ":") strip all whitespace compact payloads; when indent is set the default item separator is already , with no trailing space, but pass separators explicitly if you want ":" without its space too
allow_nan=False refuse NaN/Infinity (invalid strict JSON) production writes — fail loudly on your side

sort_keys=True + indent=2 is the combination that makes JSON files diffable: two runs that produce the same data produce byte-identical files, so git diff shows exactly what changed. The ticket report in 7.1 relies on this.

3.2 What survives a round trip — and what doesn't#

JSON's type system is smaller than Python's. The mapping is mostly clean, but six traps catch people constantly (the demo below also shows the raw_decode extraction of 3.3 and the NaN case, numbered 6 and 7 in its comments):

python
# p3b_types.py — what survives a JSON round trip, and what doesn't
import json
from datetime import date
from decimal import Decimal
from pathlib import Path

WORK = Path("json09"); WORK.mkdir(exist_ok=True)

# 1. Tuples become lists; dict keys must be str/int/float/bool/None
print(json.dumps({"point": (1, 2), "n": 3}))
print(type(json.loads(json.dumps({"point": (1, 2)}))["point"]))
print(json.dumps({1: "one", True: "yes", None: "nothing"}))   # keys stringified!

# 2. Unsupported types raise TypeError — sets, bytes, datetime, Decimal
for obj in ({1, 2}, b"bytes", date(2026, 11, 6), Decimal("19.99")):
    try:
        json.dumps(obj)
    except TypeError as e:
        print(type(obj).__name__, "->", e)

# 3. default= converts what you choose, for free types like date/Decimal/set
def default(o):
    if isinstance(o, (date, Decimal)):
        return str(o)
    if isinstance(o, set):
        return sorted(o)
    raise TypeError(f"not JSON-serialisable: {type(o).__name__}")

print(json.dumps({"when": date(2026, 11, 6), "price": Decimal("19.99"),
                  "tags": {"b", "a"}}, default=default))

# 4. parse_float keeps decimals exact; parse_int can widen ints
print(json.loads('{"price": 19.99}', parse_float=Decimal)["price"], type(json.loads('{"price": 19.99}', parse_float=Decimal)["price"]).__name__)

# 5. object_hook runs on every decoded object — revive tagged values
def default2(o):
    if isinstance(o, Decimal):
        return {"__decimal__": str(o)}
    if isinstance(o, date):
        return {"__date__": o.isoformat()}
    raise TypeError

def hook(d):
    if set(d) == {"__decimal__"}:
        return Decimal(d["__decimal__"])
    if set(d) == {"__date__"}:
        return date.fromisoformat(d["__date__"])
    return d

s = json.dumps({"price": Decimal("19.99"), "when": date(2026, 11, 6)},
               default=default2)
print("encoded :", s)
back = json.loads(s, object_hook=hook)
print("decoded :", back, "| types:", type(back["price"]).__name__, type(back["when"]).__name__)

# 6. raw_decode: pull ONE JSON value out of surrounding prose (model output!)
text = 'Sure! Here is the ticket: {"id": 7, "status": "open"} — hope that helps!'
dec = json.JSONDecoder()
obj, end = dec.raw_decode(text, text.index("{"))
print("extracted:", obj, "| stopped at char", end, "of", len(text))

# 7. NaN: Python writes/reads it by default; strict JSON forbids it
print("dumps NaN :", json.dumps({"v": float("nan")}))
try:
    json.dumps({"v": float("nan")}, allow_nan=False)
except ValueError as e:
    print("allow_nan=False ->", e)
Output14 lines
{"point": [1, 2], "n": 3}
<class 'list'>
{"1": "yes", "null": "nothing"}
set -> Object of type set is not JSON serializable
bytes -> Object of type bytes is not JSON serializable
date -> Object of type date is not JSON serializable
Decimal -> Object of type Decimal is not JSON serializable
{"when": "2026-11-06", "price": "19.99", "tags": ["a", "b"]}
19.99 Decimal
encoded : {"price": {"__decimal__": "19.99"}, "when": {"__date__": "2026-11-06"}}
decoded : {'price': Decimal('19.99'), 'when': datetime.date(2026, 11, 6)} | types: Decimal date
extracted: {'id': 7, 'status': 'open'} | stopped at char 53 of 72
dumps NaN : {"v": NaN}
allow_nan=False -> Out of range float values are not JSON compliant: nan

Reading the traps:

  1. Tuples → lists. json has no tuple type; (1, 2) round-trips as [1, 2]. If the distinction matters (coordinates vs list), revive it with object_hook or store {"__tuple__": [...]} yourself.
  2. Dict keys are stringified. int, float, bool and None keys become the strings "1", "1.5", "true" and "null". The demo's dict shows a Python-level collision on top: 1 == True (and they hash alike), so {1: "one", True: "yes", None: "nothing"} is already a two-key dict, {1: "yes", None: "nothing"}, before JSON ever sees it — which is why the output has "1": "yes" and no "true". On the way back, keys stay strings: "1" doesn't become 1 automatically. APIs that need integer IDs either quote them in JSON or you convert with int(k) after parsing.
  3. default= handles unknown types on write. It's called for any object the encoder doesn't know; return a JSON-safe replacement (here str(date) and sorted(set)). For dataclasses the one-liner is dataclasses.asdict — json.dumps(ticket, default=lambda o: dataclasses.asdict(o) if dataclasses.is_dataclass(o) else str(o)) turns the whole object into nested plain dicts. Raise TypeError inside default for anything you don't want silently converted — that's how you catch a forgotten field.
  4. parse_float=Decimal keeps decimals exact on read. Without it every 19.99 becomes a binary float (19.989999…); with it you get Decimal('19.99'). parse_int similarly intercepts integer literals (useful for huge IDs — see 00.6 §2.4).
  5. object_hook runs on every decoded object. It's the decode-side twin of default: each {...} in the input passes through your function on the way out. The tagged-value pattern above ({"__decimal__": "19.99"}) is the standard way to smuggle non-JSON types through a JSON document and revive them losslessly.
  6. NaN/Infinity aren't JSON. Python's dumps emits them by default (producing documents strict parsers reject) and loads accepts them; allow_nan=False makes writes fail loudly instead. The read-side counterpart is parse_constant, a loads hook invoked for exactly those literals — json.loads(text, parse_constant=lambda x: None) maps NaN/Infinity/-Infinity to None rather than floats you have to check for downstream. 00.6 §2.2 has the full trap story — the short version: check math.isnan before serialising computed numbers, or pass allow_nan=False so the failure happens on your side.

3.3 JSONDecodeError forensics and raw_decode#

json.JSONDecodeError (a ValueError subclass) tells you where parsing failed: .msg (what was expected), .doc (the input), .pos, .lineno, .colno. Quote all of them in error reports — "line 3, column 13: Expecting value" is debuggable; "invalid JSON" is not. In production code you wrap json.loads at the boundary:

python
try:
    data = json.loads(text)
except json.JSONDecodeError as e:
    raise ValueError(f"response was not valid JSON at line {e.lineno} col {e.colno}: {e.msg}") from e

The subtler problem is JSON buried in prose — the classic LLM failure where the model wraps its answer in "Sure! Here's the JSON:" or adds a Markdown fence. Two tools, in order of preference:

  • json.JSONDecoder().raw_decode(text, idx) parses one JSON value starting at idx and returns (obj, end_index) — it stops exactly where the value ends, ignoring trailing prose. Find the first { (or [) and call it. This is the same machinery 03.4 uses for its extractor.
  • text[text.find("{"):text.rfind("}") + 1] — the naive slice. It breaks when prose after the JSON contains a brace, or when the reply holds two objects. Fine for a prototype; raw_decode is the fix.

The deeper point, which 03.4 builds an entire lesson on: a successful json.loads means syntax, not shape or truth. The next layer is checking the structure — which you can do by hand (below) or properly with a schema validator.

3.4 Validating JSON structure by hand#

Before Pydantic (01B.6) or JSON Schema (00.6 §2.9), the pragmatic middle ground is a small safe-traversal helper: walk a nested dict/list structure by a path of keys, returning None (or a default) instead of raising KeyError/TypeError/IndexError when the shape isn't what you expected:

python
# safe_get.py — navigate nested JSON without trusting the shape
def safe_get(obj, *path, default=None):
    """obj['a']['b'][0]['c'] via safe_get(obj, 'a', 'b', 0, 'c')."""
    for key in path:
        if isinstance(key, int):
            if not isinstance(obj, list) or not -len(obj) <= key < len(obj):
                return default
            obj = obj[key]
        else:
            if not isinstance(obj, dict) or key not in obj:
                return default
            obj = obj[key]
    return obj

# an API response where 'items' might be missing, a dict, or a list of dicts
resp = {"data": {"items": [{"sku": "A-1", "price": 9.99}, {"sku": "B-2"}]}}
print(safe_get(resp, "data", "items", 0, "price"))        # 9.99
print(safe_get(resp, "data", "items", 1, "price"))        # None — key absent
print(safe_get(resp, "data", "items", 5, "sku"))          # None — index out of range
print(safe_get(resp, "meta", "total", default=0))         # 0 — 'meta' missing entirely
print(safe_get(resp, "data", "items", "price"))           # None — 'price' isn't an index into a list
Output5 lines
9.99
None
None
0
None

3.5 JSON Lines: streaming read and write#

JSON Lines (JSONL, .jsonl) is one complete JSON value per line, newline-terminated — 00.6 §2.6 introduced it; here's the Python that makes it useful at scale. It's the format of provider batch files (03.9), eval datasets (10A.2 §1.4), and structured logs (11A.1 §2.6).

python
# p3c_jsonl.py — JSON Lines: streaming write/read, dedupe, line-forensics
import json
from pathlib import Path

WORK = Path("jsonl09"); WORK.mkdir(exist_ok=True)
records = [
    {"id": "t-001", "input": "My invoice total is wrong", "expected": "billing"},
    {"id": "t-002", "input": "How do I reset my password?", "expected": "account"},
    {"id": "t-003", "input": "The app crashes on launch", "expected": "bug"},
    {"id": "t-001", "input": "My invoice total is wrong", "expected": "billing"},  # dupe!
    {"id": "t-004", "input": "Invoice total wrong, again", "expected": "billing"},
]

path = WORK / "cases.jsonl"
with path.open("w", encoding="utf-8") as f:          # one compact object per line
    for r in records:
        f.write(json.dumps(r, ensure_ascii=False) + "\n")

# generator: stream lines, parse each independently, dedupe by id preserving order
def iter_jsonl(path):
    with path.open(encoding="utf-8") as f:
        for n, line in enumerate(f, 1):
            yield n, json.loads(line)

seen, kept = set(), []
for n, obj in iter_jsonl(path):
    if obj["id"] in seen:
        print(f"line {n}: duplicate id {obj['id']!r} — skipped")
        continue
    seen.add(obj["id"])
    kept.append(obj)
print("kept:", len(kept), "unique ids:", len(seen))

# a malformed line breaks only itself — catch per line
bad = WORK / "mixed.jsonl"
bad.write_text(
    '{"id": "a"}\n'
    '{"id": "b", broken}\n'
    '{"id": "c"}\n', encoding="utf-8")
with bad.open(encoding="utf-8") as f:
    for n, line in enumerate(f, 1):
        try:
            obj = json.loads(line)
            print(f"line {n}: ok id={obj['id']}")
        except json.JSONDecodeError as e:
            print(f"line {n}: BAD ({e.msg} at col {e.colno}) — skipped")

# size sanity: file is small text; nothing was ever fully loaded
print("file bytes:", path.stat().st_size)
Output6 lines
line 4: duplicate id 't-001' — skipped
kept: 4 unique ids: 4
line 1: ok id=a
line 2: BAD (Expecting property name enclosed in double quotes at col 13) — skipped
line 3: ok id=c
file bytes: 384

The write side is f.write(json.dumps(obj) + "\n") per record — or, if you already have an open file in a with block and want compactness, json.dump(obj, f, separators=(",", ":")) then f.write("\n"). The read side is a generator (01A.5): for line in f yields one line at a time, json.loads parses it, and the whole file never exists in memory. That combination — line-delimited format + streaming parser — is why JSONL beat giant JSON arrays for ML data: append-friendly, diff-friendly, failure-local (one bad line breaks one record), and constant-memory.

Two discipline points: (1) catch JSONDecodeError per line, not around the whole loop — a malformed line should be reported and skipped, not kill a 10-hour job; (2) when writing, use ensure_ascii=False if your text is non-English — \uXXXX escapes are valid but unreadable, and they roughly double the size of CJK text (a \uXXXX escape is 6 bytes; a CJK character is 3 bytes in UTF-8 — worse still for 2-byte characters like Cyrillic). For batch API files specifically, each line is a complete request object and the file must be UTF-8 — 03.9 shows the real builders.

3.6 Pretty-printing, diffing, and large-JSON awareness#

  • python3 -m json.tool is the zero-code pretty-printer: cat response.json | python3 -m json.tool reformats any JSON on stdin — the fastest way to eyeball an API response in a terminal. Add --sort-keys for canonical order. From Python 3.14 the shorter python3 -m json is the preferred spelling (json.tool is soft-deprecated but still works) and its output is coloured on a terminal.
  • For diffs, the habit is json.dumps(data, indent=2, sort_keys=True) — canonical form means git diff shows semantic changes, not formatting noise. The report.json in 7.1 is written this way.
  • Large JSON awareness: json.loads needs the whole document as a str in memory — a 2 GB .json will hurt. If you must process huge JSON, the options are: (a) get the data as JSONL instead (stream it — the format exists for this reason); (b) ijson (third-party, uv add ijson) yields events from a stream without loading the doc; (c) if it's your format, switch to JSONL on write. Provider APIs already return streamed JSON you never hold whole (03.3).

Part 4: CSV in depth#

CSV is the format of spreadsheets and exports: flat rows of fields separated by a delimiter, one header row naming the columns. It's everywhere in AI work — training-data exports, support-ticket dumps, feature stores, billing extracts — and it's the format that breaks most often, because the spec is a convention, not a law. The csv module handles the parsing; this part teaches it properly.

4.1 reader/writer vs DictReader/DictWriter#

The module has two interfaces. The positional one (csv.reader/csv.writer) yields lists of strings — fast, faithful, and what you want when column order is fixed. The mapping one (csv.DictReader/csv.DictWriter) wraps each row in a dict keyed by the header — what you want for records, because it survives column reordering and reads like your ticket dicts from 01A.4:

python
# p4_csv.py — csv reader/writer, DictReader/DictWriter, quoting, dialects, BOM, types
import csv
from pathlib import Path

WORK = Path("csv09"); WORK.mkdir(exist_ok=True)

tickets = [
    {"id": "T-101", "subject": "Cannot log in", "priority": "1", "tags": "login,urgent"},
    {"id": "T-102", "subject": "Invoice, wrong total", "priority": "2", "tags": "billing"},
    {"id": "T-103", "subject": "App \"crashes\" on launch", "priority": "3", "tags": "bug"},
    {"id": "T-104", "subject": "Multi\nline note here", "priority": "1", "tags": "docs"},
]

# --- DictWriter: header + rows; csv handles commas, quotes and newlines ----------
out = WORK / "tickets.csv"
with out.open("w", newline="", encoding="utf-8") as f:   # newline="" is REQUIRED for csv
    w = csv.DictWriter(f, fieldnames=["id", "subject", "priority", "tags"])
    w.writeheader()
    w.writerows(tickets)
print("--- raw file bytes (note quoting) ---")
print(out.read_text(encoding="utf-8"))

# --- DictReader: rows come back as dicts of STRINGS ------------------------------
with out.open(newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["id"], "|", type(row["priority"]).__name__, "|", repr(row["subject"][:30]))

# --- reader() positional form ----------------------------------------------------
with out.open(newline="", encoding="utf-8") as f:
    rows = list(csv.reader(f))
print("header:", rows[0], "| row count incl header:", len(rows))

# --- a semicolon dialect (European CSV) ------------------------------------------
euro = WORK / "euro.csv"
euro.write_text("name;city;score\nAna;Lisboa;9,5\nBo;Porto;7,0\n", encoding="utf-8")
with euro.open(newline="", encoding="utf-8") as f:
    for row in csv.reader(f, delimiter=";"):
        print("euro row:", row)

# --- BOM: utf-8-sig strips the Excel BOM; plain utf-8 leaves  ---------------
bom = WORK / "bom.csv"
with bom.open("w", newline="", encoding="utf-8-sig") as f:
    csv.writer(f).writerows([["id", "name"], ["1", "Ana"]])
print("first 3 bytes:", bom.read_bytes()[:3])
with bom.open(newline="", encoding="utf-8") as f:
    print("utf-8 header   :", next(csv.reader(f)))
with bom.open(newline="", encoding="utf-8-sig") as f:
    print("utf-8-sig header:", next(csv.reader(f)))

# --- missing values: short rows fill with restval ---------------------------------
short = WORK / "short.csv"
short.write_text("id,name,city\n1,Ana\n2,Bo,Porto,EXTRA\n", encoding="utf-8")
with short.open(newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f, restval="<missing>"):
        print("short row:", row)

# --- type conversion is YOUR job: everything arrives as str -----------------------
def to_int(s):
    try:
        return int(s)
    except ValueError:
        return None

with out.open(newline="", encoding="utf-8") as f:
    typed = [{**r, "priority": to_int(r["priority"])} for r in csv.DictReader(f)]
print("typed priorities:", [r["priority"] for r in typed], type(typed[0]["priority"]).__name__)
Output22 lines
--- raw file bytes (note quoting) ---
id,subject,priority,tags
T-101,Cannot log in,1,"login,urgent"
T-102,"Invoice, wrong total",2,billing
T-103,"App ""crashes"" on launch",3,bug
T-104,"Multi
line note here",1,docs

T-101 | str | 'Cannot log in'
T-102 | str | 'Invoice, wrong total'
T-103 | str | 'App "crashes" on launch'
T-104 | str | 'Multi\nline note here'
header: ['id', 'subject', 'priority', 'tags'] | row count incl header: 5
euro row: ['name', 'city', 'score']
euro row: ['Ana', 'Lisboa', '9,5']
euro row: ['Bo', 'Porto', '7,0']
first 3 bytes: b'\xef\xbb\xbf'
utf-8 header   : ['\ufeffid', 'name']
utf-8-sig header: ['id', 'name']
short row: {'id': '1', 'name': 'Ana', 'city': '<missing>'}
short row: {'id': '2', 'name': 'Bo', 'city': 'Porto', None: ['EXTRA']}
typed priorities: [1, 2, 3, 1] int

Read the raw file carefully — it's the whole format in five lines:

  • T-101,...,1,"login,urgent" — a field containing a comma is quoted so the comma isn't a delimiter.
  • T-102,"Invoice, wrong total",2,billing — same rule.
  • T-103,"App ""crashes"" on launch",3,bug — a field containing a quote doubles it ("") inside the quotes.
  • T-104,"Multi + newline + line note here",1,docs — a quoted field may contain a literal newline; the record spans two physical lines. This is why for line in f + split(",") can never parse CSV correctly.

DictReader gives you dicts keyed by header, and every value is a str — type(row["priority"]).__name__ printed str even though the file says 1. Type conversion is your job (01A.4's dicts don't care, but your arithmetic does). The to_int helper shows the safe pattern: try the conversion, return None (or collect an error — 7.3) on failure.

For ragged rows: DictReader fills missing trailing fields with restval, which is None by default, so the key is present with a None value (the demo passed restval="<missing>" to make gaps visible). The distinction matters downstream: row.get("city") returns None both for a short row and for a column that does not exist at all, but "city" in row is True in the first case and False in the second. Extra fields land under the restkey — None by default, so they surface as row[None] — as a list: {'id': '2', ..., None: ['EXTRA']} above. Pass restkey="extra" to give the overflow list a real name. Both are silent data problems worth checking in validation.

The write side has the mirror-image trap: DictWriter defaults to extrasaction="raise", so a dict carrying a key that isn't in fieldnames dies with ValueError: dict contains fields not in fieldnames — loud, which is what you want. extrasaction="ignore" silently drops unexpected keys; reach for it only when discarding fields is genuinely intended, never as a way to silence the error.

4.2 Quoting, dialects, delimiters — the format's traps#

CSV has no official spec — just RFC 4180's light conventions plus decades of spreadsheet variants. The csv module's answer is the dialect: a named bundle of delimiter, quotechar, escapechar, doublequote, skipinitialspace, lineterminator, quoting.

  • Default dialect excel: , delimiter, " quotechar, \r\n line terminator, QUOTE_MINIMAL (quote only when needed — the output above).
  • csv.excel_tab: same but \t delimiter — the "TSV" dialect.
  • Custom dialects: register once with csv.register_dialect("semi", delimiter=";", quoting=csv.QUOTE_MINIMAL) then pass dialect="semi" — or just pass delimiter=";" per call as the demo did.
  • European CSVs use ; because , is the decimal separator (9,5 not 9.5) — the euro.csv demo. If a "CSV" parses into one column, suspect the wrong delimiter before suspecting corruption.
  • csv.Sniffer().sniff(sample) guesses delimiter/quote from a text sample — handy for unknown exports, but verify its guess on real data; it's a heuristic, not a guarantee.
  • The quoting= constants control what the writer quotes: csv.QUOTE_MINIMAL (default), QUOTE_ALL, QUOTE_NONNUMERIC (quote every non-number — on read it converts unquoted fields to float, which surprises people), QUOTE_NONE (never quote; needs an escapechar), and, since Python 3.12, QUOTE_STRINGS and QUOTE_NOTNULL, which tell None apart from the empty string (None writes as nothing, "" as ""). Run on ["a", 1, None, "x y"], QUOTE_NONNUMERIC writes "a",1,"","x y" while QUOTE_STRINGS writes "a",1,,"x y".
  • csv.field_size_limit() is a limit you will hit with AI data: a single field larger than 131,072 characters (the default) raises _csv.Error: field larger than field limit (131072) — typical for a CSV that stores whole documents or long model outputs in one cell. Raise it deliberately with csv.field_size_limit(1_000_000) (the call returns the old limit), and treat a field that large as a sign that JSONL may be the better container. Also worth knowing: csv.reader(f, strict=True) raises csv.Error on malformed input (for example an unterminated quote, unexpected end of data) instead of guessing, which is what you want for data you intend to trust.
python
import csv, io
rows = list(csv.reader(io.StringIO("a,b\n1,\"x,y\"\n")))
print(rows)   # [['a', 'b'], ['1', 'x,y']]

The hand-written-CSV failure, for real — a file where someone typed quotes around a comma but the csv module still splits on it because the quoting was malformed:

python
# p8_gallery.py — gallery demos: hand-written CSV pitfalls, csv \r\n bytes
import csv
from pathlib import Path

WORK = Path("gal09"); WORK.mkdir(exist_ok=True)

# 1. A CSV written BY HAND without quoting: the comma splits the field
bad = WORK / "bad.csv"
bad.write_text("id,subject,note\n1,Login fails,user said \"help, now\" please\n", encoding="utf-8")
with bad.open(newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print("hand-written row:", row)

# 2. What csv.writer actually emits: \r\n line endings by default
good = WORK / "good.csv"
with good.open("w", newline="", encoding="utf-8") as f:
    csv.writer(f).writerows([["a", "b"], ["1", "2"]])
print("raw bytes:", good.read_bytes())
Output2 lines
hand-written row: {'id': '1', 'subject': 'Login fails', 'note': 'user said "help', None: [' now" please']}
raw bytes: b'a,b\r\n1,2\r\n'

The "help, now" field lost its second half into the None overflow key — silently wrong data, exactly the kind that poisons an eval set. And raw bytes shows the default lineterminator='\r\n': csv.writer emits CRLF, the Excel convention. That's legal CSV and csv.reader handles it fine because you opened with newline="" — which is the next section.

4.3 newline="", encodings and the BOM#

Two arguments on open() exist almost solely for CSV:

  • newline="" — disables universal-newline translation so the csv module sees the file's raw line endings. The csv docs require it on both read and write: without it, embedded newlines inside quoted fields get translated inconsistently and rows can split or merge. It's the single most-forgotten csv argument.
  • encoding="utf-8-sig" — the BOM-aware UTF-8 codec. Excel writes a BOM (byte-order mark: bytes EF BB BF) at the start of "CSV UTF-8" files; read as plain utf-8 the BOM becomes an invisible \ufeff glued to your first header name — {'\ufeffid': '1', ...} instead of {'id': '1', ...} — and row["id"] raises KeyError on every row. utf-8-sig on read strips it; on write it emits it (useful when the file's destination is Excel). The demo shows all three states: b'\xef\xbb\xbf' bytes, '\ufeffid' header under utf-8, clean 'id' under utf-8-sig.

The pragmatic rule for CSV in the wild: read with newline="", encoding="utf-8-sig" — it handles BOM'd and plain UTF-8 files identically, and utf-8-sig is a strict superset of utf-8 for reading (files without a BOM read the same). Write with newline="", encoding="utf-8" unless the consumer is Excel.

4.4 CSV vs JSON vs JSONL vs Parquet — and the format table#

CSV's weakness is that it only models flat tables of strings. The moment your data is nested, typed, or huge, a different format wins:

Format Shape Strengths Weaknesses Where you meet it
CSV/TSV flat table, all strings universal, spreadsheet-native, tiny no types, no nesting, quoting traps, no schema exports, simple datasets, Excel round-trips
JSON one document, nested self-describing, typed-ish, universal whole doc in memory, no streaming API bodies, configs, small datasets
JSONL one JSON value per line streaming, append-friendly, failure-local no random access, slightly larger eval sets, logs, batch files (3.5)
Parquet columnar binary + schema compact, typed, fast analytics scans needs pyarrow/pandas (01B.11), not stdlib data lakes, ML feature stores (10A.2 §1.4)
YAML/TOML/INI config documents human-editable, comments not for data at scale config files (Part 5)

Decision rule: tabular + small + human → CSV; nested or typed → JSON; big + append/stream → JSONL; analytics-scale → Parquet. The ticket toolkit writes both report.json (nested summary) and report.csv (flat rows) from the same data — different consumers, different formats, one source of truth.


Part 5: Other formats you'll meet#

Reference

JSON, JSONL and CSV cover most data files, but configs and archives live next door. Quick tour of the rest — enough to recognise and use them, not to master them.

5.1 TOML with tomllib#

TOML is the config format of pyproject.toml, Cargo.toml, uv.toml — key/value pairs with [sections] and nested tables. Python 3.11+ ships tomllib in the standard library — read-only (loads, load); writing TOML is a third-party job (tomli-w). Reading is what you need 95% of the time:

python
# p5_formats.py — tomllib, configparser, pickle (+pickletools), gzip, zipfile, os.environ
import configparser, gzip, io, os, pickle, pickletools, zipfile
import tomllib
from pathlib import Path

WORK = Path("fmt09"); WORK.mkdir(exist_ok=True)

# --- TOML via tomllib (stdlib since 3.11, read-only) ------------------------------
toml_text = """
[project]
name = "triage"
requires-python = ">=3.11"
dependencies = ["httpx"]

[tool.ruff]
line-length = 100
"""
data = tomllib.loads(toml_text)
print("toml project name:", data["project"]["name"])
print("toml ruff line-length:", data["tool"]["ruff"]["line-length"])
(WORK / "pyproject.toml").write_text(toml_text, encoding="utf-8")
with (WORK / "pyproject.toml").open("rb") as fh:
    print("tomllib.load:", tomllib.load(fh)["project"]["name"])
Output3 lines
toml project name: triage
toml ruff line-length: 100
tomllib.load: triage

Note tomllib.load takes a binary file object (open("rb")) — TOML is UTF-8 by spec, and the parser wants bytes. tomllib.loads takes a str. The result is plain dicts/lists/scalars — same shapes as json.loads, so your downstream code doesn't care which format it came from.

5.2 YAML awareness — pyyaml and the safe_load rule#

YAML is the other big config format: indentation-based, comment-friendly, used by GitHub Actions, Kubernetes, Docker Compose, OpenAPI, and prompt libraries (04.10 keeps prompts as YAML front-matter). It's not in the standard library — uv add pyyaml (6.0.3 as of November 2026). Two rules:

  1. Use yaml.safe_load, never yaml.load. The dangerous form is yaml.load(stream, Loader=yaml.Loader) — and yaml.unsafe_load — which can construct arbitrary Python objects, the same code-execution surface as pickle. Since PyYAML 6.0 yaml.load requires the Loader argument, so a bare yaml.load(text) just raises TypeError — but old code and Stack Overflow snippets still pass Loader=yaml.Loader, and that is exactly the unsafe path. safe_load only produces plain dicts/lists/scalars. This is the YAML equivalent of the pickle rule below; treat every YAML file from outside your repo as untrusted input.
  2. YAML is a superset of JSON — any .json file is valid YAML, so yaml.safe_load can read JSON too (though json.loads is faster and stricter). The reverse is false.
python
import yaml   # pip/uv install pyyaml — third-party, NOT run in this lesson
cfg = yaml.safe_load(Path("config.yaml").read_text(encoding="utf-8"))
print(cfg["model"], cfg["limits"]["max_tokens"])
# Example output (illustrative — pyyaml not run here):
# claude-haiku-5-5 4096

5.3 INI with configparser#

Older configs — .ini, .cfg, setup.cfg — use [section] + key = value. configparser is stdlib and reads them into nested dicts (config["section"]["key"], all strings, with config.getint()/getfloat()/getboolean() for typed reads). It's fine for flat settings; it can't express nesting, lists or types — if you need those, TOML or JSON is the better format. Two gotchas: configparser lowercases keys by default (optionxform), which surprises people porting camelCase configs; and its default interpolation treats % as special, so a value such as a URL with %20 or a password containing % raises InterpolationSyntaxError on read — escape it as %%, or create the parser with ConfigParser(interpolation=None).

5.4 pickle: never unpickle untrusted data#

pickle serialises arbitrary Python objects — including class instances, functions' state, and (fatally) code. pickle.loads doesn't just read data; it reconstructs objects by calling whatever the file says to call. A pickle file is a program. pickletools.dis shows the opcodes — you can literally see GLOBAL 'os system' style instructions in a malicious file (the exact listing varies slightly between Python versions).

The demo continues p5_formats.py — its header (the import line and WORK = Path("fmt09")) is the listing at the top of §5.1, and it covers everything the fragments below need (pickle, pickletools, io, gzip, zipfile, os). Run the whole file for real:

python
# (from p5_formats.py — imports and WORK defined in the §5.1 header)
obj = {"tickets": [1, 2, 3], "meta": ("a", 1)}
blob = pickle.dumps(obj)
print("pickle round trip:", pickle.loads(blob) == obj, "| bytes:", len(blob))
# --- pickletools.dis (first opcodes) ---
#     0: \x80 PROTO      5
#     2: \x95 FRAME      40
#    11: }    EMPTY_DICT
#    ...
#    49: u        SETITEMS   (MARK at 13)
#    50: .    STOP
# highest protocol among opcodes = 4

shelve (a tiny DBM-backed dict persisted via pickle) and sqlite3 (real SQL in a file — 00.7 teaches it) are the "small persistence" neighbours: shelve inherits pickle's untrusted-data rule; sqlite3 is safe and is what the KV store in 7.6 would grow into.

5.5 Compression and archives: gzip, zipfile#

Logs, JSONL dumps and CSV exports get big fast — compressing them is one line:

python
# (from p5_formats.py — gzip/zipfile/WORK from the §5.1 header)
report = ("ticket,priority\n" + "\n".join(f"T-{i},high" for i in range(200)) + "\n") * 20
raw = report.encode()
packed = gzip.compress(raw)
print("gzip: raw", len(raw), "-> packed", len(packed), "-> round trip ok:", gzip.decompress(packed) == raw)
# gzip: raw 42120 -> packed 760 -> round trip ok: True
with gzip.open(WORK / "report.csv.gz", "rt", encoding="utf-8") as f:
    print("gzip.open first line:", f.readline().strip())
# gzip.open first line: ticket,priority

zpath = WORK / "bundle.zip"
with zipfile.ZipFile(zpath, "w", zipfile.ZIP_DEFLATED) as z:
    z.writestr("data/a.txt", "alpha")
    z.writestr("data/b.txt", "beta")
with zipfile.ZipFile(zpath) as z:
    print("zip names:", z.namelist(), "| a.txt:", z.read("data/a.txt"))
# zip names: ['data/a.txt', 'data/b.txt'] | a.txt: b'alpha'

gzip.open(path, "rt", encoding="utf-8") is the beautiful part: it decompresses and decodes text transparently, so a .csv.gz reads exactly like a .csv — line by line, streaming, constant memory. zipfile reads/writes .zip archives in memory or on disk; for reading zips from untrusted sources, extract to a sandboxed temp dir and validate member paths — zips can contain ../ traversal entries and decompression bombs (the 05.3 corpus demo hits a 948:1 ratio).

5.6 Environment variables with os.environ (preview)#

Configuration that differs per machine — data directories, feature flags, API endpoints — belongs in the environment, not hard-coded paths. os.environ is the process's environment-variable mapping:

python
# (from p5_formats.py — os/WORK from the §5.1 header)
os.environ["TRIAGE_DATA_DIR"] = "demo-data"          # pretend it came from the shell/.env
print("env var:", os.environ.get("TRIAGE_DATA_DIR"))
print("missing var default:", os.environ.get("NO_SUCH_VAR", "fallback"))
# env var: demo-data
# missing var default: fallback

os.environ["X"] raises KeyError if unset; os.environ.get("X", default) is the safe read; os.environ.setdefault and os.environ.pop complete the API. In a shell you'd export TRIAGE_DATA_DIR=demo-data (or put it in .env — 01B.2 owns .env files, pydantic-settings, and the full secret-hygiene story; the shell side is 00.2). The habit to build now: paths and knobs come from os.environ.get(...) with a sane default, never from literals buried in code.

5.7 Choosing a format — the decision table#

You have... Use Because
Flat table, humans edit it, small CSV universal, spreadsheet-native
Nested/typed data, one document JSON self-describing, every language parses it
Big record stream, append/log/eval/batch JSONL streaming, failure-local, constant memory
Columnar analytics at scale Parquet compact, typed, fast scans (needs pyarrow)
Human-edited app config TOML (pyproject) or YAML (k8s/CI) comments, sections, readable diffs
Flat key=value settings, legacy INI via configparser stdlib, ubiquitous
Arbitrary Python objects, own cache pickle powerful — and dangerous if untrusted
Big text/binary blob, bandwidth matters gzip/.gz transparent compression
Many small files as one download zipfile standard archive
Secrets/endpoints per environment os.environ never in code, never in git

Part 6: Robust file handling#

The difference between a script and a tool is what happens when the file isn't there, isn't what you expected, or half-exists. This part is the checklist.

6.1 The error catalogue#

Exception Means Typical cause Right response
FileNotFoundError path doesn't exist typo, missing export, wrong CWD check exists() if absence is normal; else fail loudly with the path in the message
IsADirectoryError opened a dir as a file user-supplied path guard is_file()
PermissionError OS refused chmod, read-only FS, sandbox config problem — don't retry blindly
UnicodeDecodeError bytes ≠ declared encoding legacy export, wrong encoding= detect/fix encoding (2.2)
json.JSONDecodeError malformed JSON truncated write, prose-wrapped model output raw_decode / validate-and-retry (3.3)
csv.Error malformed CSV (rare — it's lenient), or field larger than field limit (131072) a single huge cell, or strict=True meeting bad quoting raise the limit deliberately with a concrete number, e.g. csv.field_size_limit(1_000_000) (4.2); sys.maxsize overflows on some platforms
OSError (parent) everything above — catch OSError for "any filesystem problem" at the boundary

The discipline: catch the specific exception at the boundary (per file, per row), attach context (str(path) in the message), and decide per case — skip-and-report for batch data (7.3), fail-fast for a single required input.

6.2 Path traversal and untrusted paths#

Any time a user, model output, or external file supplies a path — "save the report to X", an uploaded filename, a tool argument — the string is hostile until proven otherwise. ../../etc/passwd isn't a path, it's an escape. The defence is two lines:

python
# p6_traversal.py — never trust a user-supplied path: resolve + is_relative_to
from pathlib import Path

root = Path("uploads").resolve()
(root / "reports").mkdir(parents=True, exist_ok=True)
(root / "reports" / "q3.pdf").write_bytes(b"%PDF-fake")

def safe_join(root: Path, user_path: str) -> Path | None:
    """Join user_path under root, or return None if it escapes."""
    candidate = (root / user_path).resolve()      # resolve() collapses ../ and symlinks
    if not candidate.is_relative_to(root):
        return None
    return candidate

for user_path in ["reports/q3.pdf", "../../etc/passwd", "reports/../../secret.txt", "../outside.txt"]:
    p = safe_join(root, user_path)
    print(f"{user_path!r:30} -> {p.relative_to(root) if p else 'REJECTED (escapes root)'}")
Output4 lines
'reports/q3.pdf'               -> reports/q3.pdf
'../../etc/passwd'             -> REJECTED (escapes root)
'reports/../../secret.txt'     -> REJECTED (escapes root)
'../outside.txt'               -> REJECTED (escapes root)

Why each piece matters: (root / user_path) alone lets .. climb out; .resolve() collapses .. and resolves symlinks (the classic bypass — a symlink inside uploads/ pointing at /etc); is_relative_to(root) is the final bouncer. This is the same guard 08A.15 puts around its file tools and 12.5 §3.2.4 covers as an LLM-output vulnerability — model-chosen paths are untrusted input exactly like user input.

6.3 Idempotent scripts, --dry-run, and skip reporting#

Idempotent means safe to run twice with the same result — the property every batch job needs (05.9 is the deep version). For file scripts the habits are:

  • Check before you write. "Does the output already exist and match?" — skip or overwrite deliberately, never accidentally.
  • Write-then-flip for multi-file updates (2.5): a manifest plus data files that update together, or a crash leaves a consistent pair.
  • --dry-run flag: run the whole pipeline, print what would be written/skipped/deleted, write nothing. It's ~10 lines (argparse + if not args.dry_run: around the write calls) and prevents the "oops I just regenerated the dataset" conversation. 05.9 §4.5 demos it on an ingestion pipeline.
  • Report what you skipped. Every batch processor should end with processed N, skipped M, failed K and why — the JSONL dedupe (7.4) and CSV→JSON converter (7.3) both do this. Silent skipping is how bad data ships.

6.4 Race conditions and locking (awareness)#

Two processes writing the same file can interleave bytes or lose updates (read-modify-write isn't atomic). os.replace makes a single rename atomic but doesn't protect the read-decide-write cycle. Real locking (fcntl.flock, filelock package, or a proper database) is needed when multiple processes share state — for single-process scripts and sequential batch jobs, atomic writes + idempotent design cover you. Know the boundary; don't cargo-cult locks.


Part 7: Putting it together#

Deep-dive

7.1 The ticket toolkit, assembled#

The running example across this module — tickets as dicts, classify with rules, summarise with Counter, write JSON and CSV reports — comes together here. This is the file-I/O layer of the triage package that 01A.10 finishes:

python
# p7_ticket.py — the running example: tickets.csv -> classify -> report.json + report.csv
# Pure stdlib, deterministic fixture. Run: python3 p7_ticket.py
import csv, json
from collections import Counter
from pathlib import Path

WORK = Path("triage09"); WORK.mkdir(exist_ok=True)

# --- fixture: a small tickets.csv (what an export from a helpdesk looks like) ---
CSV_TEXT = """id,subject,body,priority
T-101,Cannot log in,"I keep getting 'invalid password' after reset",1
T-102,Invoice total wrong,"Charged twice for March, see attached",2
T-103,App crashes on launch,"Instant crash, version 2.4.1, Windows 11",3
T-104,How do I export data?,"Looking for the export button",2
T-105,Password reset email never arrives,"Checked spam too",1
T-106,Billing question about VAT,"Do you charge VAT on invoices?",2
T-107,Crash when uploading PDF,"Happens with files over 10MB",3
T-108,Feature request: dark mode,"Would love a dark theme",4
"""
(WORK / "tickets.csv").write_text(CSV_TEXT, encoding="utf-8")

KEYWORDS = {
    "login": ("log in", "login", "password", "sign in"),
    "billing": ("invoice", "billing", "charged", "vat", "payment"),
    "bug": ("crash", "bug", "error", "broken", "fails"),
    "docs": ("how do i", "export", "where is", "documentation"),
}

def classify(text: str) -> str:
    t = text.lower()
    for category, words in KEYWORDS.items():
        if any(w in t for w in words):
            return category
    return "other"

def load_tickets(path: Path) -> list[dict]:
    with path.open(newline="", encoding="utf-8") as f:
        rows = []
        for row in csv.DictReader(f):
            row["priority"] = int(row["priority"])
            row["category"] = classify(f"{row['subject']} {row['body']}")
            rows.append(row)
        return rows

tickets = load_tickets(WORK / "tickets.csv")
by_cat = Counter(t["category"] for t in tickets)
by_pri = Counter(t["priority"] for t in tickets)

# --- report.json: the machine-readable summary -----------------------------------
report = {
    "total": len(tickets),
    "by_category": dict(sorted(by_cat.items())),
    "by_priority": {str(k): v for k, v in sorted(by_pri.items())},
    "tickets": [{"id": t["id"], "category": t["category"], "priority": t["priority"]}
                for t in tickets],
}
(WORK / "report.json").write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")

# --- report.csv: the enriched rows -------------------------------------------------
with (WORK / "report.csv").open("w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["id", "subject", "priority", "category"])
    w.writeheader()
    for t in tickets:
        w.writerow({"id": t["id"], "subject": t["subject"],
                    "priority": t["priority"], "category": t["category"]})

# --- summary table on stdout ---------------------------------------------------------
print(f"{'id':6} {'pri':3} {'category':8} subject")
for t in tickets:
    print(f"{t['id']:6} {t['priority']:<3} {t['category']:8} {t['subject']}")
print("-" * 46)
print("by category:", dict(sorted(by_cat.items())))
print("by priority:", dict(sorted(by_pri.items())))
print("wrote:", (WORK / "report.json").name, "and", (WORK / "report.csv").name)
flowchart LR
    A["tickets.csv<br/>(DictReader, newline='', utf-8)"] --> B["list of dicts<br/>+ classify() + int(priority)"]
    B --> C["report.json<br/>json.dumps indent=2 sort_keys"]
    B --> D["report.csv<br/>DictWriter newline=''"]
    B --> E["stdout summary<br/>Counter tables"]
Output13 lines
id     pri category subject
T-101  1   login    Cannot log in
T-102  2   billing  Invoice total wrong
T-103  3   bug      App crashes on launch
T-104  2   docs     How do I export data?
T-105  1   login    Password reset email never arrives
T-106  2   billing  Billing question about VAT
T-107  3   bug      Crash when uploading PDF
T-108  4   other    Feature request: dark mode
----------------------------------------------
by category: {'billing': 2, 'bug': 2, 'docs': 1, 'login': 2, 'other': 1}
by priority: {1: 2, 2: 3, 3: 2, 4: 1}
wrote: report.json and report.csv

Every habit from this lesson is in that one file: newline="" + encoding="utf-8" on the CSV read, int() type conversion per row, json.dumps(indent=2, sort_keys=True) for a diffable report, DictWriter with newline="" for the CSV output, and Path everywhere instead of string concatenation.

7.2 Mini-project: log analyser#

Text logs → counts. The analyser streams the file line by line (constant memory on a 10 GB log), matches each line with a regex, normalises volatile bits (ids, hosts, timings) into a signature so repeats group together, and Counters the results:

python
# p7_logan.py — mini-project: analyse an app log -> counts by level and error signature
import re
from collections import Counter
from pathlib import Path

WORK = Path("logan09"); WORK.mkdir(exist_ok=True)

LOG = """2026-11-04 10:00:01 INFO  worker-1 started
2026-11-04 10:00:02 INFO  worker-1 loaded 3 tickets
2026-11-04 10:00:03 ERROR worker-1 db timeout after 30s (host=db-1)
2026-11-04 10:00:04 WARN  worker-1 retrying request 3/5
2026-11-04 10:00:05 ERROR worker-1 db timeout after 30s (host=db-1)
2026-11-04 10:00:06 INFO  worker-1 request ok id=9912
2026-11-04 10:00:07 ERROR worker-2 auth failed for user=u-77
2026-11-04 10:00:08 WARN  worker-2 slow query 812ms
2026-11-04 10:00:09 ERROR worker-1 db timeout after 30s (host=db-2)
2026-11-04 10:00:10 INFO  worker-1 shutdown
"""
log = WORK / "app.log"
log.write_text(LOG, encoding="utf-8")

LINE = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} (?P<level>\w+)\s+(?P<msg>.*)$")
# normalise volatile bits (ids, hosts, timings) so repeats group together
def signature(msg: str) -> str:
    msg = re.sub(r"host=[^\s)]+", "host=<host>", msg)     # stop at the closing ")"
    msg = re.sub(r"\b\d+(?:ms|s)\b", "<duration>", msg)    # 30s, 812ms
    msg = re.sub(r"\bid=\d+", "id=<n>", msg)
    msg = re.sub(r"user=\S+", "user=<user>", msg)
    return msg

levels, errors = Counter(), Counter()
with log.open(encoding="utf-8") as f:               # stream: works on huge logs
    for line in f:
        m = LINE.match(line)
        if not m:
            continue
        levels[m["level"]] += 1
        if m["level"] == "ERROR":
            errors[signature(m["msg"])] += 1

print("levels:", dict(levels))
print("top error signatures:")
for sig, n in errors.most_common(3):
    print(f"  {n}x {sig}")
Output4 lines
levels: {'INFO': 4, 'ERROR': 4, 'WARN': 2}
top error signatures:
  3x worker-1 db timeout after <duration> (host=<host>)
  1x worker-2 auth failed for user=<user>

The signature() normalisation is the whole trick: three db timeout errors on different hosts collapse to one signature → 3x, which is what an on-call engineer wants to see. Swap the regex for your log format; the structure (stream → match → signature → Counter) is the reusable part. This is the same shape as real log analysis in 11A.1 — there the "signature" is a span attribute and the "Counter" is a metric.

7.3 Mini-project: CSV→JSON converter#

CSV in, validated JSON out, bad rows reported not fatal — the "validate at the boundary" pattern in miniature:

python
# p7_csv2json.py — mini-project: CSV -> validated JSON + error report
# Bad rows are collected, not fatal: the converter reports and continues.
import csv, json
from pathlib import Path

WORK = Path("c2j09"); WORK.mkdir(exist_ok=True)

CSV_TEXT = """id,email,score
u1,ana@example.com,9.5
u2,not-an-email,7
u3,bo@example.com,abc
u4,,8.0
u5,cy@example.com,8.5
"""
src = WORK / "users.csv"
src.write_text(CSV_TEXT, encoding="utf-8")

def valid_email(s: str) -> bool:
    return "@" in s and "." in s.split("@")[-1]

records, errors = [], []
with src.open(newline="", encoding="utf-8") as f:
    for n, row in enumerate(csv.DictReader(f), start=2):   # line 1 is the header
        problems = []
        if not row["id"]:
            problems.append("missing id")
        if not valid_email(row["email"]):
            problems.append(f"bad email {row['email']!r}")
        try:
            score = float(row["score"])
        except ValueError:
            problems.append(f"bad score {row['score']!r}")
            score = None
        if problems:
            errors.append({"line": n, "id": row["id"], "problems": problems})
            continue
        records.append({"id": row["id"], "email": row["email"], "score": score})

(WORK / "users.json").write_text(json.dumps(records, indent=2) + "\n", encoding="utf-8")
with (WORK / "errors.csv").open("w", newline="", encoding="utf-8") as f:
    w = csv.DictWriter(f, fieldnames=["line", "id", "problems"])
    w.writeheader()
    for e in errors:
        w.writerow({"line": e["line"], "id": e["id"], "problems": "; ".join(e["problems"])})

print(f"valid: {len(records)} | rejected: {len(errors)}")
for e in errors:
    print(f"  line {e['line']} ({e['id'] or '?'}): {'; '.join(e['problems'])}")
print("wrote users.json and errors.csv")
Output5 lines
valid: 2 | rejected: 3
  line 3 (u2): bad email 'not-an-email'
  line 4 (u3): bad score 'abc'
  line 5 (u4): bad email ''
wrote users.json and errors.csv

Three design choices worth copying: enumerate(..., start=2) so error line numbers match the file (header is line 1); accumulate problems per row so one row can fail for several reasons; and write the rejects to their own errors.csv so nothing is silently dropped. This is the same "collect-and-report" shape 01A.8 uses for robust parsing — validation at the boundary, errors as data.

7.4 Mini-project: JSONL de-duplicator#

JSONL in, de-duplicated JSONL out, every skip logged — the streaming dedupe from 3.5 as a reusable function:

python
# p7_jsonldedupe.py — mini-project: dedupe a JSONL file by a key field
# Streams the input, keeps first occurrence, reports every skip.
import json
from pathlib import Path

WORK = Path("jd09"); WORK.mkdir(exist_ok=True)
src = WORK / "events.jsonl"
src.write_text(
    '{"id": "e1", "kind": "click", "ts": 100}\n'
    '{"id": "e2", "kind": "view",  "ts": 101}\n'
    '{"id": "e1", "kind": "click", "ts": 102}\n'   # dupe id, different ts
    '{"id": "e3", "kind": "view",  "ts": 103}\n'
    '{"id": "e2", "kind": "view",  "ts": 104}\n', encoding="utf-8")

def dedupe_jsonl(src: Path, dst: Path, key: str = "id"):
    seen = set()
    kept = skipped = bad = 0
    with src.open(encoding="utf-8") as fin, dst.open("w", encoding="utf-8") as fout:
        for n, line in enumerate(fin, 1):
            try:
                obj = json.loads(line)
            except json.JSONDecodeError:
                bad += 1
                print(f"  line {n}: unparseable — skipped")
                continue
            k = obj.get(key)
            if k in seen:
                skipped += 1
                print(f"  line {n}: duplicate {key}={k!r} — skipped")
                continue
            seen.add(k)
            fout.write(json.dumps(obj) + "\n")
            kept += 1
    return kept, skipped, bad

out = WORK / "events.deduped.jsonl"
k, s, b = dedupe_jsonl(src, out)
print(f"kept {k}, skipped {s} duplicates, {b} bad lines -> {out.name}")
Output3 lines
  line 3: duplicate id='e1' — skipped
  line 5: duplicate id='e2' — skipped
kept 3, skipped 2 duplicates, 0 bad lines -> events.deduped.jsonl

Note obj.get(key) not obj[key] — a line missing the key shouldn't KeyError the whole run; decide whether "no key" is a skip or an error for your data. The seen set holds only keys, so memory stays bounded by unique count, not file size — for truly huge files an external sort or a disk-backed set (e.g. sqlite3, the growth path 5.4 names) is the next step — a Bloom filter only approximates membership and its false positives would silently drop unique records. This covers eval sets and logs comfortably.

7.5 Mini-project: folder indexer#

Walk a directory tree, emit a manifest.json — the seed of every ingestion pipeline (05.1 owns the full version):

python
# p7_indexer.py — mini-project: index a folder tree into manifest.json
import hashlib, json
from collections import Counter
from pathlib import Path

WORK = Path("idx09"); WORK.mkdir(exist_ok=True)
tree = WORK / "corpus"
for rel, content in {
    "docs/readme.md": "# Docs\n",
    "docs/api/v1.md": "# API v1\n",
    "data/tickets.csv": "id,subject\n1,x\n",
    "data/notes.txt": "remember the milk\n",
    "empty/.gitkeep": "",
}.items():
    p = tree / rel
    p.parent.mkdir(parents=True, exist_ok=True)
    p.write_text(content, encoding="utf-8")

def sha256_short(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()[:12]

entries = []
for p in sorted(tree.rglob("*")):               # deterministic order
    if p.is_file():
        entries.append({
            "path": p.relative_to(tree).as_posix(),   # forward slashes everywhere
            "bytes": p.stat().st_size,
            "sha256": sha256_short(p),
        })

manifest = {"root": "corpus", "count": len(entries), "files": entries}
(WORK / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")

print(f"{len(entries)} files indexed")
for e in entries:
    print(f"  {e['bytes']:>3}B  {e['sha256']}  {e['path']}")
print("extensions:", dict(Counter(Path(e["path"]).suffix for e in entries)))
Output7 lines
5 files indexed
   18B  86bb148f5efa  data/notes.txt
   15B  27ce3b0923de  data/tickets.csv
    9B  8f0733736099  docs/api/v1.md
    7B  b8c2322c9fb6  docs/readme.md
    0B  e3b0c44298fc  empty/.gitkeep
extensions: {'.txt': 1, '.csv': 1, '.md': 2, '': 1}

Three details that make it production-shaped: sorted(rglob("*")) so the manifest is deterministic (stable diffs — same trick as sort_keys); p.relative_to(tree).as_posix() so paths are data/tickets.csv not data\\tickets.csv on Windows; and sha256 per file so the next run can detect changed files by hash — that's the content-hash change detection 05.9 §2.2 builds on.

7.6 Mini-project: a tiny JSON key-value store#

The capstone of file I/O: a persistent dict on disk, with atomic writes so a crash can't corrupt it:

python
# p7_kvstore.py — mini-project: tiny JSON key-value store with atomic writes
import json, os, tempfile
from pathlib import Path

WORK = Path("kv09"); WORK.mkdir(exist_ok=True)
DB = WORK / "store.json"

def load() -> dict:
    if not DB.exists():
        return {}
    return json.loads(DB.read_text(encoding="utf-8"))

def save(data: dict) -> None:
    fd, tmp = tempfile.mkstemp(dir=DB.parent, suffix=".tmp", text=True)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, sort_keys=True)
            f.write("\n")
            f.flush()
            os.fsync(f.fileno())      # push contents to stable storage before the rename
        os.replace(tmp, DB)          # atomic: readers see old or new, never half
        # for machine-crash durability also fsync the directory — see §2.5
    except BaseException:
        os.unlink(tmp)
        raise

def put(key: str, value) -> None:
    data = load(); data[key] = value; save(data)

def get(key: str):
    return load().get(key)

def delete(key: str) -> bool:
    data = load()
    if key not in data:
        return False
    del data[key]; save(data); return True

put("last_ticket", "T-108")
put("counts", {"open": 3, "closed": 5})
print("get last_ticket:", get("last_ticket"))
print("get counts     :", get("counts"))
print("delete missing :", delete("nope"))
print("delete counts  :", delete("counts"))
print("final store    :", DB.read_text(encoding="utf-8").strip().replace("\n", " "))
Output5 lines
get last_ticket: T-108
get counts     : {'closed': 5, 'open': 3}
delete missing : False
delete counts  : True
final store    : {   "last_ticket": "T-108" }

save() is the 2.5 pattern in its final form: mkstemp in the same directory (required — os.replace can't cross filesystems), write + flush/os.fsync + close (the durability step from §2.5 — two lines, cheap insurance), os.replace (atomic rename), and os.unlink(tmp) in the except so a failed write doesn't litter temp files. One side effect to know: mkstemp creates its file with mode 0600 (owner-only), so after os.replace the store carries those permissions rather than your umask's default — usually what you want for a private store, and fixable with shutil.copymode(old, tmp) before the replace if a shared file must keep its mode. load()-modify-save() per operation is O(file) per write — fine for a small store, wrong for high write rates (that's what SQLite is for). This is the honest boundary: JSON-on-disk is a toy persistence layer, and knowing when to graduate to sqlite3 (00.7) is the lesson.


Seven file-handling sins behind the "works on my machine", silent-corruption and 3 a.m. page — each with real output:

python
# mistakes_gallery.py — the seven sins
import csv
import datetime
import io
import json
import os
import sys
from pathlib import Path

WORK = (Path.cwd() / "gallery09").resolve()
(WORK / "data").mkdir(parents=True, exist_ok=True)

# 1. encoding surprises: UTF-8 bytes are not latin-1, and ascii refuses them
(WORK / "cafe.txt").write_bytes("café — naïve".encode("utf-8"))
print("1a. same bytes as utf-8  :", (WORK / "cafe.txt").read_text(encoding="utf-8"))
print("1b. same bytes as latin-1:", (WORK / "cafe.txt").read_text(encoding="latin-1"))
try:
    (WORK / "cafe.txt").read_text(encoding="ascii")
except UnicodeDecodeError as e:
    print("1c. same bytes as ascii  ->", type(e).__name__)

# 2. relative paths resolve against the CWD, not the script's location
(WORK / "data" / "in.csv").write_text("a,b\n", encoding="utf-8")
os.chdir(WORK / "data")
print("2a. cwd=data/: Path('in.csv').exists() ->", Path("in.csv").exists())
os.chdir(WORK)
print("2b. cwd=root: Path('in.csv').exists() ->", Path("in.csv").exists(),
      "| Path('data/in.csv').exists() ->", Path("data/in.csv").exists())

# 3. overwriting files: mode "w" truncates with no warning and no backup
p = WORK / "config.json"
p.write_text('{"version": 1, "keep_me": true}', encoding="utf-8")
p.write_text('{"version": 2}', encoding="utf-8")
print("3. after the second write:", p.read_text(encoding="utf-8").strip())

# 4. unclosed files: small writes sit in the buffer — the disk sees nothing yet
f = open(WORK / "buffered.txt", "w", encoding="utf-8")
f.write("written but not flushed")
print("4a. before close, disk sees:", repr((WORK / "buffered.txt").read_text(encoding="utf-8")))
f.close()
print("4b. after close,  disk sees:", repr((WORK / "buffered.txt").read_text(encoding="utf-8")))

# 5. reading a whole file into memory: fine at MB, fatal at GB
big = WORK / "big.txt"
with big.open("w", encoding="utf-8") as fh:
    for i in range(50_000):
        fh.write(f"row {i} " + "x" * 96 + "\n")
data = big.read_text(encoding="utf-8")
print("5a. read_text() -> one str:", len(data), "chars,",
      sys.getsizeof(data) // 1_000_000, "MB")
with big.open(encoding="utf-8") as fh:
    total = sum(len(line) for line in fh)
print("5b. line-by-line total:", total, "chars, bounded memory")

# 6. CSV quoting bugs: hand-rolled joins corrupt rows
rows = [("id", "note"), ("1", "has, comma"), ("2", 'say "hi"'), ("3", "line1\nline2")]
hand = "\n".join(",".join(str(c) for c in r) for r in rows)
print("6a. hand-joined CSV:")
print(hand)
buf = io.StringIO()
csv.writer(buf).writerows(rows)
print("6b. csv.writer output:")
print(buf.getvalue(), end="")

# 7. json.dump of unsupported types
try:
    json.dumps({"when": datetime.datetime(2026, 1, 1)})
except TypeError as e:
    print("7. json.dumps(datetime) ->", type(e).__name__ + ":", e)
Output23 lines
1a. same bytes as utf-8  : café — naïve
1b. same bytes as latin-1: café — naïve
1c. same bytes as ascii  -> UnicodeDecodeError
2a. cwd=data/: Path('in.csv').exists() -> True
2b. cwd=root: Path('in.csv').exists() -> False | Path('data/in.csv').exists() -> True
3. after the second write: {"version": 2}
4a. before close, disk sees: ''
4b. after close,  disk sees: 'written but not flushed'
5a. read_text() -> one str: 5338890 chars, 5 MB
5b. line-by-line total: 5338890 chars, bounded memory
6a. hand-joined CSV:
id,note
1,has, comma
2,say "hi"
3,line1
line2
6b. csv.writer output:
id,note
1,"has, comma"
2,"say ""hi"""
3,"line1
line2"
7. json.dumps(datetime) -> TypeError: Object of type datetime is not JSON serializable
  1. Encoding surprises — the same bytes are three different texts depending on the codec, and latin-1 never fails: it just lies. Omitting encoding= defers to locale.getpreferredencoding() — UTF-8 on macOS/Linux, often a legacy code page on Windows. Always pass encoding="utf-8" (2.2).
  2. Relative-path surprises — Path("in.csv") resolved against the CWD: True from data/, False from the parent. "Works on my machine" is usually a working-directory difference — anchor inputs to Path(__file__).parent, an environment variable or an argparse argument (1.1).
  3. Overwriting files — the second write_text truncated config.json to {"version": 2}; keep_me is gone with no warning and no backup. "w" means "destroy, then write"; "x" refuses to overwrite, and the 2.5 pattern writes-then-replaces.
  4. Unclosed files — before close() the disk saw '': the write sat in the buffer. Short scripts survive on CPython's refcounting, but loops and servers leak descriptors and a crash mid-buffer loses the data. with guarantees the close (2.3).
  5. Reading huge files into memory — read_text() produced one ~5 MB str; at log-file scale that's a MemoryError. Stream instead: iterate lines, readline() or sized chunks — same answer, bounded memory (2.4).
  6. CSV quoting bugs — the hand-joined file split has, comma into two fields, left say "hi" ambiguous and broke line1\nline2 into two records. Never join CSV by hand; csv.writer quotes exactly what needs quoting (4.1).
  7. json.dump of unsupported types — TypeError: Object of type datetime is not JSON serializable. JSON has no date, set or Decimal; convert first (.isoformat(), str(), or a default= function) (3.2).

Common misconceptions#

Misconception Reality
"A relative path points to the same file everywhere." It resolves against the working directory, not the script. Path("data/x.csv") means different things run from different folders — anchor with Path(__file__) or config.
"open() defaults to UTF-8 everywhere." Only since Python 3.15 (PEP 686). On 3.11–3.14 Windows uses the locale code page (often cp1252) — always pass encoding="utf-8".
"If json.loads succeeds, the data is fine." It proves syntax only. Shape, types and semantics need validation — safe_get, then Pydantic (01B.6).
"JSON round-trips Python objects faithfully." Tuples→lists, keys→strings, sets/dates/Decimals→TypeError. default=/object_hook/parse_float cover the gaps.
"json.dump(data, "file.json") writes the file." The second arg must be an open file object — json.dump(data, f) inside with open(...), or Path.write_text(json.dumps(data)).
"CSV is just split(",")." Fields contain commas, quotes and literal newlines — quoting is semantic. Use csv.reader/DictReader with newline="".
"Every CSV column arrives typed." Everything is str. int()/float() conversions are yours, with error handling per row.
"A BOM is invisible, so it doesn't matter." Under plain utf-8 it becomes \ufeff glued to your first header — KeyError on every row. Read CSV as utf-8-sig.
"pickle is just a serialisation format." It's executable code on load — never unpickle untrusted data. JSON/JSONL/safetensors for anything crossing a trust boundary.
"Writing a file is atomic if it's one write() call." Not across a crash — the file can be half-written. Write to temp + os.replace for atomicity, plus fsync before the rename and on the directory after if it must survive a machine crash.
"shutil.rmtree is just rm -r with training wheels." It deletes recursively with no undo — validate the path first, print what you're deleting.
"JSONL is just JSON in a trench coat." It's a different contract: one value per line, no commas, streamable. A .jsonl fed to json.loads fails Extra data; a .json array fed line-by-line fails differently.
"Big files need readlines() into a list." That loads everything. for line in f streams — constant memory on any size.
"Path.resolve() is only for making paths absolute." It also collapses .. and symlinks — which is exactly why it's required before is_relative_to in traversal checks.
"YAML is safe because it's 'just config'." yaml.load(..., Loader=yaml.Loader) and yaml.unsafe_load construct arbitrary Python objects — yaml.safe_load only produces plain types.

Key takeaways#

  • Paths are objects, not strings. pathlib.Path joins with /, splits into name/stem/suffix/parent/parts, navigates with iterdir/glob/rglob, and anchors with resolve()/relative_to(). Relative paths resolve against the working directory — anchor data files to Path(__file__) or config, never assume the CWD.
  • Read and write text with encoding="utf-8" explicitly — always, both directions. with blocks guarantee closing. newline="" is required for CSV.
  • Match the read strategy to the file: read_text() for small docs, for line in f for row-shaped data (logs, JSONL, CSV — constant memory), fixed-size chunks for binary.
  • Write safely: temp file + os.replace for atomic updates, "a" mode for append-only logs, "x" mode when the file must not exist, and "w" knowing it truncates.
  • JSON: dumps/loads for strings, dump/load for file objects. indent=2, sort_keys=True for diffable files. default=/parse_float/object_hook for the type gaps. JSONDecodeError gives line/col; raw_decode extracts one value from prose. JSONL streams one object per line — the format of eval sets and batch files.
  • CSV: DictReader/DictWriter for records, newline="" always, utf-8-sig for reading (BOM), delimiter/dialect for variants, field_size_limit for giant cells, and you do the type conversion — everything arrives as str.
  • Other formats: tomllib (stdlib, read-only) for TOML, yaml.safe_load (never yaml.load) for YAML, configparser for INI, gzip/zipfile for compression, os.environ for config — and never pickle.load untrusted data.
  • Robustness: catch specific exceptions at the boundary, guard user paths with resolve() + is_relative_to(), write idempotent scripts with --dry-run, and always report what you skipped.

Where you'll use this in the AI path#

This lesson is the file layer everything else stands on:

Skill from this lesson Used in
pathlib, read_text/write_text, rglob 05.1 Data Sources and Ingestion — local files are the first ingestion source
JSONL streaming read/write 03.9 Async, Concurrency and Batch — provider batch files are JSONL; 10A.2 §1.4 — eval datasets are JSONL in git
json.loads + raw_decode + validation 03.4 Structured Output — parsing model responses; 01B.6 — the schema layer on top
CSV DictReader, type conversion, error collection 05.3 — CSV/TSV as a parsing target; every tabular export in the path
Atomic writes, idempotent scripts, --dry-run 05.9 Ingestion Pipelines — write-then-flip manifests; 10A.8 — reproducible eval runs
JSONL trace/log records 11A.1 §2.6 — observability data is JSONL; 03.10 — structured logging
Binary reads, magic bytes 03.6 Multimodal Input — attachments are bytes→base64; 05.2 — PDFs are binary streams
os.environ for paths/config 01B.2 — the full configuration story; 03.1 — .env and keys
Path traversal guard 12.5 §3.2.4 — model-chosen paths are untrusted; 08A.15 — file-tool sandboxing

Terms introduced in this lesson#

Term One-line definition
pathlib.Path Object-oriented filesystem path: join with /, inspect with .name/.parent/.parts
Working directory (CWD) The directory a process was launched from; what relative paths resolve against
__file__ Module-level variable holding the path of the file being executed
resolve() Make a path absolute, collapse .., follow symlinks
relative_to() / is_relative_to() Re-anchor a path under a base / test containment (the traversal guard)
glob / rglob / iterdir Pattern-match paths in one dir / recursively / list all children (dotfiles included — pathlib doesn't treat them specially)
PurePath / PurePosixPath / PureWindowsPath Path manipulation with no filesystem access; per-OS flavours for parsing foreign paths
stem / suffix / name / parent Path anatomy: tickets.csv → stem tickets, suffix .csv
encoding= The codec mapping bytes↔str on text I/O; always pass "utf-8"
newline="" Disable newline translation — required for csv module correctness
with / context manager Guarantees close() on exit, normally or via exception
Atomic write Write to temp + os.replace so readers see old-or-new, never half (+ fsync for machine-crash durability)
"a" / "x" / "r+" modes Append / exclusive-create / read+write file modes
io.StringIO / BytesIO In-memory file objects — same interface, no disk
seek / tell Move/query the file position
Magic bytes The signature bytes at a file's start (%PDF, PK, \x89PNG) identifying its type
json.dump vs dumps Write into a file object vs return a string
default= Callback converting non-JSON types on write
object_hook / object_pairs_hook Callback transforming each decoded object / receiving raw pairs first (duplicate-key detection)
parse_float / parse_int / parse_constant Callbacks intercepting JSON number literals / the NaN/Infinity constants on read
JSONDecodeError Exception carrying msg/lineno/colno/pos for parse forensics
raw_decode Parse one JSON value from a position, ignoring trailing prose
JSON Lines (JSONL) One complete JSON value per line — the streaming record format
safe_get Path-based nested-dict access returning a default instead of raising
CSV dialect Named bundle of delimiter/quotechar/lineterminator/quoting rules
DictReader / DictWriter CSV rows as dicts keyed by header / dicts back to CSV
extrasaction DictWriter policy for unexpected dict keys: "raise" (default) or "ignore"
restval / restkey Fill value for missing trailing fields / name for the overflow-field list
quoting= / QUOTE_* Which fields the csv writer quotes: MINIMAL (default), ALL, NONNUMERIC, NONE, plus STRINGS and NOTNULL (3.12+)
csv.field_size_limit() Per-field size cap (131,072 characters by default); exceeding it raises csv.Error
BOM / utf-8-sig Byte-order mark prefix; the codec that strips/emits it
tomllib Stdlib TOML parser (3.11+, read-only)
yaml.safe_load YAML parse restricted to plain types — the only safe load
Path traversal ../ escape from a intended root; defended by resolve() + is_relative_to()
Idempotent script Safe to re-run: same inputs → same outputs, no duplicate side effects
--dry-run Run the pipeline, report what would change, write nothing

Exercises#

Work through these against the fixtures the snippets create (demo09/, json09/, csv09/, triage09/…), or build your own. Solutions are in <details>; runnable ones were executed for real (outputs shown).

  1. Path anatomy. Without running code, predict name, stem, suffix, parent and parts for Path("data/2026/q4/tickets-2026-11.csv"). Then verify with p1_paths.py-style code.
Solution

name = tickets-2026-11.csv, stem = tickets-2026-11, suffix = .csv, parent = data/2026/q4, parts = ('data', '2026', 'q4', 'tickets-2026-11.csv') (as a relative path; absolute adds the cwd prefix). with_suffix(".json") gives data/2026/q4/tickets-2026-11.json — note with_suffix replaces only the last suffix, so archive.tar.gz → archive.tar.json, not archive.json.

  1. Count JSONL lines. Write a function that walks a directory and returns the total line count across all *.jsonl files, printing per-file counts. Run it on a tree you create.
Solution
python
from pathlib import Path

# fixture: a directory tree containing *.jsonl files (plus a non-matching file)
tree = Path("ex09") / "logs"
for name, lines in {"a.jsonl": 2, "b.jsonl": 3, "c.txt": 9}.items():
    (tree / name).parent.mkdir(parents=True, exist_ok=True)
    (tree / name).write_text('{"x": 1}\n' * lines, encoding="utf-8")

total = 0
for p in sorted(tree.rglob("*.jsonl")):
    with p.open(encoding="utf-8") as f:
        n = sum(1 for _ in f)
    total += n
    print(f"  {p.name}: {n} lines")
print("  total:", total)

Real output on a 3-file fixture:

text
  a.jsonl: 2 lines
  b.jsonl: 3 lines
  total: 5

sum(1 for _ in f) counts lines without building a list — the streaming habit.

  1. Exact money. A JSON payload has {"price": 19.99}. Load it so price is a Decimal, not a float, and print its type.
Solution
python
import json
from decimal import Decimal
obj = json.loads('{"price": 19.99}', parse_float=Decimal)
print(obj["price"], type(obj["price"]).__name__)
# 19.99 Decimal
  1. Extract JSON from prose. Given 'Here is the result: {"status": "ok", "n": 3} Hope that helps!', extract the object with raw_decode — don't use find("{")/rfind("}") slicing.
Solution
python
import json
text = 'Here is the result: {"status": "ok", "n": 3} Hope that helps!'
obj, end = json.JSONDecoder().raw_decode(text, text.index("{"))
print(obj, "| ended at", end)
# {'status': 'ok', 'n': 3} | ended at 44
  1. Typed CSV rows. Read a CSV with columns id,qty where qty may be empty or non-numeric; produce dicts with qty as int or None, never raising.
Solution
python
import csv
from pathlib import Path

# fixture: qty is a number, empty, and non-numeric
src = Path("qty.csv")
src.write_text("id,qty\nA,3\nB,\nC,lots\n", encoding="utf-8")

rows = []
with src.open(newline="", encoding="utf-8") as f:
    for r in csv.DictReader(f):
        try:
            qty = int(r["qty"]) if r["qty"] else None
        except ValueError:
            qty = None
        rows.append({"id": r["id"], "qty": qty})
print(rows)
# [{'id': 'A', 'qty': 3}, {'id': 'B', 'qty': None}, {'id': 'C', 'qty': None}]
  1. Skip bad JSONL lines. Given a .jsonl file where line 2 is malformed, write a loop that parses each line, skips-and-reports bad ones, and counts good/bad.
Solution
python
import json
from pathlib import Path

# fixture: line 2 is malformed
path = Path("mixed.jsonl")
path.write_text('{"id": "a"}\n{"id": "b", broken}\n{"id": "c"}\n', encoding="utf-8")

good = bad = 0
with path.open(encoding="utf-8") as f:
    for n, line in enumerate(f, 1):
        try:
            obj = json.loads(line)
            good += 1
        except json.JSONDecodeError as e:
            bad += 1
            print(f"line {n}: {e.msg} at col {e.colno}")
print(f"good={good} bad={bad}")
# line 2: Expecting property name enclosed in double quotes at col 13
# good=2 bad=1
  1. Traversal guard. A user supplies ../../etc/passwd as a filename under uploads/. Show why (root / name) alone is unsafe and how resolve() + is_relative_to() fixes it.
Solution
python
candidate = (root / "../../etc/passwd").resolve()
print(candidate.is_relative_to(root))   # False -> reject
# Without resolve(), Path("uploads/../../etc/passwd") still *contains* ".."
# lexically; is_relative_to on the unresolved path can be fooled. resolve()
# collapses .. and symlinks first, then the containment check is honest.
  1. BOM-proof headers. A CSV starts with bytes EF BB BF then id,name. Show the header key under utf-8 vs utf-8-sig.
Solution
python
import csv
from pathlib import Path

# fixture: a CSV whose first three bytes are the UTF-8 BOM, then header + one row
b = Path("bom.csv")
b.write_bytes(b'\xef\xbb\xbfid,name\n1,Ana\n')
with b.open(newline="", encoding="utf-8-sig") as f:
    print(next(csv.DictReader(f)))
# {'id': '1', 'name': 'Ana'}   — utf-8-sig stripped the BOM
# under plain utf-8 the first key would be '\ufeffid' instead
  1. Atomic save. Implement save_json(path, data) that writes data to path atomically (temp + os.replace), cleaning up the temp file on failure.
Solution
python
import json, os, tempfile
from pathlib import Path

def save_json(path: Path, data: dict) -> None:
    fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp", text=True)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, sort_keys=True)
            f.write("\n")
        os.replace(tmp, path)
    except BaseException:
        os.unlink(tmp)
        raise

mkstemp in path.parent keeps temp+target on the same filesystem (required for os.replace); the except removes the orphan temp.

  1. Compress a JSONL. Write 100 JSON lines, gzip them, and show the size reduction and a perfect round trip.
Solution
python
import gzip

data = b'{"a": 1}\n' * 100
packed = gzip.compress(data)
print("raw", len(data), "-> gz", len(packed), "-> ok:", gzip.decompress(packed) == data)
# raw 900 -> gz 38 -> ok: True
  1. Reading strategies. For each scenario pick whole-file / line-by-line / chunked and justify: (a) a 2 KB config JSON, (b) a 40 GB .jsonl eval set, (c) a 3 GB binary model file you're checksumming.
Solution

(a) json.load(f) whole — small enough that streaming buys nothing. (b) for line in f — constant memory regardless of size; JSONL exists for this. (c) f.read(1 << 20) chunks — binary has no line structure; feed chunks to hashlib incrementally.

  1. Format choice. Your team needs to store 50 million (user_id, event, ts) records for later analytics, appended continuously by many workers. CSV, JSON, JSONL, or Parquet — and why?
Solution

JSONL (or Parquet once you outgrow it). Append-friendly (one line per record, no rewrite), streamable on read, failure-local, and constant-memory for both writers and readers. CSV can't nest event payloads safely; a single .json document can't be appended to or streamed. At true analytics scale you'd move to Parquet — columnar, compact, typed — but JSONL is the right ingestion format and what the batch/eval pipelines in this path already use.

  1. Crash durability. Exercise 9's save_json survives a process crash. What two calls make the written file survive a machine crash (power loss), and where does each go? Implement them.
Solution
python
import json, os, tempfile
from pathlib import Path

def save_json(path: Path, data: dict) -> None:
    fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp", text=True)
    try:
        with os.fdopen(fd, "w", encoding="utf-8") as f:
            json.dump(data, f, indent=2, sort_keys=True)
            f.write("\n")
            f.flush()
            os.fsync(f.fileno())          # 1. contents durable BEFORE the rename
        os.replace(tmp, path)
        dir_fd = os.open(path.parent, os.O_RDONLY)
        try:
            os.fsync(dir_fd)              # 2. directory entry durable too (POSIX only)
        finally:
            os.close(dir_fd)
    except BaseException:
        os.unlink(tmp)
        raise

save_json(Path("durable.json"), {"b": 2, "a": 1})
print(Path("durable.json").read_text(encoding="utf-8").strip().replace("\n", " "))
# {   "a": 1,   "b": 2 }

f.flush() + os.fsync(f.fileno()) push the temp file's contents to stable storage before os.replace renames it into place; the second os.fsync on the directory fd makes the rename itself durable. The directory half is POSIX-only (Windows exposes no directory fsync) — the file half is portable and is the part that matters most. This is §2.5's durability paragraph in code.

  1. Ragged CSV, both directions. A CSV row has fewer fields than the header; another has more. Show what DictReader produces for each — naming restval and restkey — then show DictWriter refusing a dict with an unexpected key.
Solution
python
import csv, io

text = "id,name,city\n1,Ana\n2,Bo,Porto,EXTRA\n"
for row in csv.DictReader(io.StringIO(text), restval="<missing>", restkey="extra"):
    print(row)
# {'id': '1', 'name': 'Ana', 'city': '<missing>'}
# {'id': '2', 'name': 'Bo', 'city': 'Porto', 'extra': ['EXTRA']}

buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=["id", "name"])
w.writeheader()
try:
    w.writerow({"id": "3", "name": "Cy", "city": "X"})
except ValueError as e:
    print("extrasaction ->", e)
# extrasaction -> dict contains fields not in fieldnames: 'city'

restval fills the missing trailing field (the key stays present), restkey names the list that catches overflow fields — without it they'd land under row[None]. On the write side, extrasaction="raise" (the default) turns schema drift into a loud ValueError instead of silently dropping city.

  1. Pure paths and os.path recognition. Without touching the filesystem: (a) join reports/q3.csv under C:/data as a Windows path on any OS; (b) show that PurePosixPath keeps ..; (c) show the Windows rooted-relative join quirk; (d) name the os.path equivalents of the pathlib ideas.
Solution
python
from pathlib import PurePosixPath, PureWindowsPath
import os.path

print(PureWindowsPath("C:/data") / "reports" / "q3.csv")
# C:\data\reports\q3.csv  — Windows flavour, works on macOS/Linux too
print(PurePosixPath("data/../x.csv").parts)
# ('data', '..', 'x.csv')  — '..' kept, exactly like Path
print(PureWindowsPath("c:/Windows") / "/Program Files")
# c:\Program Files  — rooted-relative keeps the drive (POSIX '/' would reset)
print(os.path.join("data", "x.csv"), os.path.splitext("a.tar.gz"))
# data/x.csv ('a.tar', '.gz')  — the os.path spelling of join + suffix

PureWindowsPath/PurePosixPath manipulate paths for any OS without I/O — PurePath picks the flavour of the machine you're on. os.path.join/splitext are the older string-based equivalents you'll meet in legacy code and libraries.

  1. Giant cells and None vs empty. (a) Build a CSV in memory whose one text cell has 200,000 characters, show the default csv.Error, then raise the limit and read it. (b) On Python 3.12+, write [["id", "note"], [1, None], [2, ""]] with quoting=csv.QUOTE_STRINGS and show that None and the empty string come out differently.
Solution
python
import csv, io

big = "id,text\n1," + "x" * 200_000 + "\n"
try:
    list(csv.DictReader(io.StringIO(big)))
except csv.Error as e:
    print("default limit ->", e)
old = csv.field_size_limit(1_000_000)          # returns the previous limit
print("old limit:", old)
rows = list(csv.DictReader(io.StringIO(big)))
print("after raising:", len(rows[0]["text"]), "characters")

buf = io.StringIO()                            # QUOTE_STRINGS needs Python 3.12+
csv.writer(buf, quoting=csv.QUOTE_STRINGS).writerows([["id", "note"], [1, None], [2, ""]])
print(repr(buf.getvalue()))
Output4 lines
default limit -> field larger than field limit (131072)
old limit: 131072
after raising: 200000 characters
'"id","note"\r\n1,\r\n2,""\r\n'

None is written as nothing and "" as an explicit empty quoted string, so a reader using QUOTE_STRINGS can tell "no value" from "empty text". With the default QUOTE_MINIMAL both would come out as an empty field.


Check yourself#

  1. Why does Path("data/tickets.csv") find different files depending on where you run the script, and what's the fix?
  2. What's the difference between json.dumps and json.dump?
  3. Name three dumps arguments that make JSON files diffable and readable.
  4. What happens to a tuple, an int dict key, and a datetime when you json.dumps them?
  5. How do default= and object_hook complement each other?
  6. A model reply is Here you go: {"a": 1} — done!. Why does json.loads fail and what parses it correctly?
  7. Why is JSONL better than a giant JSON array for a 10-million-record eval set?
  8. List the three arguments csv code needs on open() and what each does.
  9. Why does DictReader return strings for every column, and what's the safe conversion pattern?
  10. A CSV's first header reads \ufeffid. What happened and what's the fix?
  11. Why is pickle.load on a downloaded file dangerous, and what should you use instead?
  12. What does os.replace give you that Path.rename/write_text alone doesn't?
  13. Show the two-line guard that stops ../../etc/passwd escaping an uploads directory.
  14. Your batch job crashed halfway and re-ran, duplicating records. Name two habits that prevent this.
  15. A CSV import dies with _csv.Error: field larger than field limit (131072). What is happening, and what are the two reasonable responses?

Further resources#

All terms are also collected in the glossary.


← 01A.8 — Errors, Exceptions, Debugging and Logging | Module 01A overview | 01A.10 — Type Hints and Writing Readable Code →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close