07. Files and data formats
Data lives in files. Before you can clean, analyze or model anything, you must find the file, open it, read it in the right format and write your results somewhere safe. This module teaches the standard library tools for that work: pathlib for paths, open() and with for reading and writing, and the csv, json and pickle modules for three common formats. Every example uses a real course file: raw sensor readings, a sales extract, nested customer records, a pipeline config, a legacy supplier list, six monthly reports and an application log.
What you will learn
Section titled “What you will learn”- Build, inspect and check file paths with
pathlib.Path, and create output folders safely. - Read and write text files with
open(),withand the right file mode, and know when a file is closed. - Tell text files from binary files, and read and write the right encoding.
- Read and write CSV files with
csv.reader,csv.DictReaderandcsv.DictWriter, and see whysplit(",")breaks. - Load and save JSON and JSON Lines, and save Python objects with
pickle, knowing why you must never load an untrusted pickle. - Walk a directory tree, process a folder of files with different column orders, and summarize a log file.
Prerequisites
Section titled “Prerequisites”- 01. Python basics: types,
print(), f-strings and type conversion. - 02. Strings and text: string methods such as
strip(),split()andstartswith(), and encoding basics. - 03. Control flow:
if,for,enumerate()andbreak. - 04. Data structures: lists, dicts, sets and nested structures.
- 05. Functions: defining functions,
sorted()withkey. - 06. Errors and debugging:
try/exceptand reading a traceback. - The course datasets in a
data/folder inside your project: Get the data.
Concepts
Section titled “Concepts”Files, paths and the working directory
Section titled “Files, paths and the working directory”A file is a named sequence of bytes on a disk. A byte is a number from 0 to 255; every file, whether it holds text, a spreadsheet or a photo, is a sequence of bytes. A directory (also called a folder) holds files and other directories. Together they form a directory tree.
A path is the address of a file or a directory. It lists the directories from a starting point to the target, separated by / (or \ on Windows):
- An absolute path starts at the root of the disk, for example
/Users/ana/project/data/sales.csvorC:\Users\ana\project\data\sales.csv. It works from anywhere, but it is different on every machine. - A relative path starts at the working directory: the folder that the terminal is in when you run
python.data/sales.csvmeans “the filesales.csvin the folderdatainside the working directory”.
This course uses relative paths, so the same code runs on every learner’s machine. Run your scripts from the project folder that contains data/. Write results to an output/ folder, never into data/: the input data stays untouched, and you can delete output/ and rerun everything.
flowchart LR
P["project/<br/>(working directory)"] --> D["data/<br/>inputs: read only"]
P --> O["output/<br/>results: safe to delete"]
P --> S["script.py"]
D --> R["reports/<br/>2024-01.csv ..."]
D --> L["logs/<br/>app.log"]
pathlib: paths as objects
Section titled “pathlib: paths as objects”The module pathlib represents a path as a Path object instead of a plain string. A Path knows its parts, joins with the / operator and works on every operating system.
from pathlib import Path
report = Path("data") / "reports" / "2024-04.csv"print(report)print(report.name, report.stem, report.suffix)print(report.parent, report.parent.name)print(report.parts)print(report.with_suffix(".json"))data/reports/2024-04.csv2024-04.csv 2024-04 .csvdata/reports reports('data', 'reports', '2024-04.csv')data/reports/2024-04.json/joins path parts. It works between aPathand a string, soPath("data") / "sales.csv"is valid.nameis the last part,stemis the name without its suffix (the extension, such as.csv), andparentis the directory that contains it.with_suffix()returns a new path with another extension. APathnever changes; its methods return new paths.
A Path can also ask the operating system about the file:
print(report.exists(), report.is_file(), report.is_dir())print(report.parent.is_dir())print(Path("data/missing.csv").exists())print(report.stat().st_size, "bytes")True True FalseTrueFalse3146 bytesstat() returns facts about the file; st_size is its size in bytes. A missing file is not an error for exists(): it returns False. An error comes only when you try to open it.
Path.cwd() returns the working directory and path.resolve() turns a relative path into an absolute one. Both give machine-specific text, so log them for debugging but do not put them in reports:
print(Path("data").resolve().is_absolute())print(Path("data").is_absolute())TrueFalseRead and write a whole file in one call
Section titled “Read and write a whole file in one call”For small text files, a Path reads and writes in one call. read_text() returns the whole file as one str. write_text() replaces the file’s content and returns the number of characters written.
Create the output folder first. mkdir(parents=True, exist_ok=True) creates any missing parent folders (parents=True) and does nothing if the folder already exists (exist_ok=True), so it is safe to call on every run.
out_dir = Path("output")out_dir.mkdir(parents=True, exist_ok=True)
note = out_dir / "note.txt"written = note.write_text("Sensor S1 checked\nSensor S2 checked\n", encoding="utf-8")print(written)print(note.read_text(encoding="utf-8"), end="")36Sensor S1 checkedSensor S2 checkedprint(..., end="") avoids a blank line, because the file text already ends with \n. The argument encoding="utf-8" says how to turn characters into bytes; Encodings explains why you always pass it.
splitlines() turns the text into a list of lines without the line breaks:
text = Path("data/readings.txt").read_text(encoding="utf-8")lines = text.splitlines()print(len(text), "characters,", len(lines), "lines")print(lines[:5])211 characters, 43 lines['21.0', '21.9', '21.4', '21.7', '22.1']read_text() loads everything into memory at once. That is fine for kilobytes or a few megabytes. For a large file, read it line by line with open().
open(), file objects and with
Section titled “open(), file objects and with”open() opens a file and returns a file object (also called a file handle): an object that reads from or writes to the file step by step. The operating system allows a program only a limited number of open files, and data written to a file may wait in memory until the file is closed. So every file you open must be closed.
The with statement does this for you. It opens the file, runs the indented block and then closes the file, even if an error happens inside the block. An object that sets something up at the start of a with block and cleans up at the end is a context manager. File objects are context managers.
with open("data/readings.txt", encoding="utf-8") as f: first = f.readline() second = f.readline()print(repr(first), repr(second))print(f.closed)'21.0\n' '21.9\n'Truereadline()reads one line and keeps its\n.repr()shows it.- After the block,
f.closedisTrue. The variablefstill exists, but the file is closed; reading from it now raisesValueError: I/O operation on closed file.
A file object is also iterable: a for loop over it gives one line at a time. Only one line is in memory at once, so this pattern works for files of any size:
count = 0with open("data/readings.txt", encoding="utf-8") as f: for line in f: if line.strip(): count += 1print(count, "non-empty lines")42 non-empty lines| Method or pattern | Returns | Use for |
|---|---|---|
for line in f: |
one line at a time, with \n |
any size of file; the default choice |
f.read() |
the rest of the file as one str |
small files |
f.read(n) |
at most n characters (bytes in binary mode) |
chunks of a large or binary file |
f.readline() |
the next line, or "" at the end |
the header line, then a loop |
f.readlines() |
a list of all lines, each with \n |
rarely; read().splitlines() is cleaner |
f.write(s) |
the number of characters written | writing; it adds no \n |
print(..., file=f) |
None |
writing lines; it adds the \n |
File modes
Section titled “File modes”The second argument of open() is the mode: a short string that says what you want to do with the file.
| Mode | Meaning | If the file exists | If it is missing |
|---|---|---|---|
"r" |
read (the default) | read from the start | FileNotFoundError |
"w" |
write | erase it, then write | create it |
"a" |
append | write at the end | create it |
"x" |
exclusive create | FileExistsError |
create it |
"r+" |
read and write | read and write from the start | FileNotFoundError |
add "b" |
binary: "rb", "wb", "ab" |
bytes instead of str |
|
add "t" |
text (the default): "rt" = "r" |
"w" is the dangerous one: it empties the file the moment it opens it. "a" adds to a log without losing old lines. "x" refuses to overwrite, which protects results that took hours to compute:
log = Path("output/run.log")with open(log, "w", encoding="utf-8") as f: f.write("run 1 started\n")with open(log, "a", encoding="utf-8") as f: f.write("run 1 finished\n")print(log.read_text(encoding="utf-8"), end="")run 1 startedrun 1 finishedwith open(log, "x", encoding="utf-8") as f: f.write("this text is never written\n")FileExistsError: [Errno 17] File exists: 'output/run.log'open() accepts a Path or a string. The error message shows the path you passed, so relative paths keep messages short and portable.
Lines and line endings
Section titled “Lines and line endings”A text file marks the end of each line with one or two invisible characters. Linux and macOS use LF (line feed, \n). Windows programs often write CRLF (carriage return plus line feed, \r\n).
In text mode, Python translates for you. When it reads, it turns \r\n and \n into \n (this is called universal newlines). When it writes, it turns \n into the line ending of the operating system. So your code always sees \n.
Two rules follow:
f.write()adds no line ending. Writef.write(line + "\n"), or useprint(line, file=f).- The
csvmodule handles line endings itself: by default its writer ends every row with\r\n, as the CSV standard (RFC 4180) asks. Open CSV files withnewline=""to switch Python’s translation off. Without it, Windows turns that\r\ninto\r\r\n, and the CSV shows an empty line after every row. When reading,newline=""lets the reader see line breaks inside quoted fields, so a review text that spans two lines stays one field.
with open("output/lines.txt", "w", encoding="utf-8") as f: f.write("S1,21.7") f.write("S2,21.9\n") print("S3", "22.4", sep=",", file=f)print(Path("output/lines.txt").read_text(encoding="utf-8").splitlines())['S1,21.7S2,21.9', 'S3,22.4']The first write() has no \n, so the first two records end up on one line. This bug is easy to make and hard to see until a later step fails.
Text and binary
Section titled “Text and binary”Every file is bytes. A text file holds bytes that represent characters, so it can be shown as text: .txt, .csv, .json, .log, .py. A binary file holds bytes in a layout that only a specific program understands: images, Excel workbooks (.xlsx), Parquet files, SQLite databases (.db) and pickle files (.pkl).
- Text mode (
"r","w") gives youstrvalues. Python decodes the bytes into characters with an encoding. - Binary mode (
"rb","wb") gives youbytesvalues, unchanged. Abytesobject is an immutable sequence of numbers from 0 to 255. Its literal starts withb:b"PAR1".
flowchart LR
B["bytes on disk<br/>b'K\xc3\xb6ln'"] -- "decode('utf-8')<br/>open(..., 'r')" --> S["str in Python<br/>'Köln'"]
S -- "encode('utf-8')<br/>open(..., 'w')" --> B
Many binary formats start with a few fixed bytes that name the format, a file signature (also called a magic number). Reading the first bytes in binary mode tells you what a file really is, whatever its name says:
for name in ["shop.db", "sales_sample.parquet", "sales_sample.xlsx", "sales.csv"]: with open(Path("data") / name, "rb") as f: head = f.read(8) print(f"{name:22} {head}")shop.db b'SQLite f'sales_sample.parquet b'PAR1\x15\x04\x15\x86'sales_sample.xlsx b'PK\x03\x04\x14\x00\x00\x00'sales.csv b'order_id'An SQLite database starts with SQLite f (SQLite format 3), a Parquet file with PAR1, and an .xlsx workbook with PK, because it is a ZIP archive of XML files. The CSV starts with readable text. Never open a binary file in text mode: decoding fails or gives garbage.
Encodings
Section titled “Encodings”An encoding is the rule that maps characters to bytes. Module 02 introduced it; here is what matters for files.
- UTF-8 can store every character in every language. It uses 1 byte for ASCII characters (
A–Z, digits, basic punctuation) and 2 to 4 bytes for others. It is the standard for the web, JSON and modern tools. Use it for every file you write. - Latin-1 (also called ISO-8859-1) uses exactly 1 byte per character and covers only Western European letters. Old databases and Excel exports often use it, or its Windows cousin cp1252.
The same text gives different bytes in different encodings:
city = "Köln"print(city.encode("utf-8"), len(city.encode("utf-8")))print(city.encode("latin-1"), len(city.encode("latin-1")))print(b"K\xc3\xb6ln".decode("utf-8"))print(b"K\xc3\xb6ln".decode("latin-1"))b'K\xc3\xb6ln' 5b'K\xf6ln' 4KölnKölnThe last line shows mojibake: garbled text that appears when bytes are decoded with the wrong encoding. ö is two bytes in UTF-8 (\xc3\xb6); read as Latin-1, each byte becomes its own character, à and ¶.
Three rules keep you safe:
- Always pass
encoding=toopen(),read_text()andwrite_text(). Without it, Python uses a default that depends on the operating system. On Windows, Python versions before 3.15 use the legacy code page (often cp1252), so the same script can read a file correctly on a Mac and fail on Windows. PEP 686 makes UTF-8 the default from Python 3.15. - Read with the encoding the file was written in. Ask the source, or look at the bytes. A
UnicodeDecodeErrormeans the encoding is wrong. - Write UTF-8. Convert legacy files once, at the start of a pipeline.
The errors= argument decides what happens with bytes that do not fit the encoding. "strict" (the default) raises an error. "replace" puts � in their place, which lets you read a damaged file and see where the damage is. Use "replace" to inspect, not to hide a wrong encoding.
Excel often saves “CSV UTF-8” with a byte order mark (BOM): the three bytes \xef\xbb\xbf at the start of the file. Read such files with encoding="utf-8-sig", which removes the BOM. With plain "utf-8", the BOM sticks to the first column name:
export_file = Path("output/excel_export.csv")export_file.write_text("store_id,city\nS01,Chicago\n", encoding="utf-8-sig")print(export_file.read_bytes()[:12])print(export_file.read_text(encoding="utf-8").splitlines()[0].split(","))print(export_file.read_text(encoding="utf-8-sig").splitlines()[0].split(","))b'\xef\xbb\xbfstore_id,'['\ufeffstore_id', 'city']['store_id', 'city']The invisible \ufeff makes the first column '\ufeffstore_id' instead of 'store_id', so a lookup by name fails. Reading with "utf-8-sig" is safe for files with and without a BOM.
CSV files and the csv module
Section titled “CSV files and the csv module”A CSV file (comma-separated values) stores a table as text: one row per line, the fields separated by a delimiter, usually a comma. The first line is often the header row with the column names.
Splitting each line on "," looks enough, but it breaks on real data. A field that contains a comma, a quote or a line break is wrapped in double quotes, for example "January 7, 2023" or "$1,299.00". This is called quoting. The csv module understands quoting; split(",") does not.
| Tool | Gives one row as | Use when |
|---|---|---|
csv.reader(f) |
a list of strings | you work by position, or the file has no header |
csv.DictReader(f) |
a dict: column name → string | the file has a header; the safe default |
csv.writer(f) |
writerow(list) |
writing rows by position |
csv.DictWriter(f, fieldnames=...) |
writerow(dict) |
writing rows by name, in a fixed column order |
import csv
with open("data/stores.csv", encoding="utf-8", newline="") as f: reader = csv.DictReader(f) print(reader.fieldnames) first = next(reader)print(first["store_id"], first["city"], first["size_sqm"])print(type(first["size_sqm"]))['store_id', 'city', 'region', 'size_sqm', 'opened']S01 Chicago 2850<class 'str'>next(reader) reads one row. Every value is a str, even "2850": CSV has no types. Convert numbers yourself with int() and float().
Writing quotes fields only when needed:
rows = [ {"store_id": "S01", "city": "Chicago", "note": "flagship, opened 2009"}, {"store_id": "S12", "city": "Denver", "note": 'says "new"'},]with open("output/stores_notes.csv", "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=["store_id", "city", "note"]) writer.writeheader() writer.writerows(rows)print(Path("output/stores_notes.csv").read_text(encoding="utf-8"), end="")store_id,city,noteS01,Chicago,"flagship, opened 2009"S12,Denver,"says ""new"""The note with a comma is wrapped in quotes. The note with quotes doubles each inner quote (""). Any CSV reader turns them back into the original text. Other delimiters work the same way: csv.reader(f, delimiter=";") reads the semicolon files that European Excel versions write, and delimiter="\t" reads TSV (tab-separated values).
JSON (JavaScript Object Notation) is a text format for nested data: objects with named fields, lists, numbers, strings, true/false and null. Web APIs, config files and many ML tools use it. The json module maps JSON types to Python types:
| JSON | Python (load) | Python (dump) |
|---|---|---|
object {"a": 1} |
dict |
dict (keys become strings) |
array [1, 2] |
list |
list or tuple |
string "S01" |
str |
str |
number 3 / 0.25 |
int / float |
int / float |
true / false |
True / False |
True / False |
null |
None |
None |
| (no equivalent) | set, date, datetime, bytes raise TypeError |
| Function | Does |
|---|---|
json.load(f) |
reads JSON from an open file, returns Python objects |
json.loads(s) |
parses a JSON string (s for string) |
json.dump(obj, f, indent=2) |
writes Python objects to an open file |
json.dumps(obj) |
returns a JSON string |
Serialization is turning an object in memory into bytes or text that you can store or send. Deserialization is the reverse. dump serializes and load deserializes.
import json
settings = {"model": "logistic_regression", "features": ("age", "plan")}text = json.dumps(settings)print(text)back = json.loads(text)print(back["features"], back == settings){"model": "logistic_regression", "features": ["age", "plan"]}['age', 'plan'] FalseThe tuple became a JSON array, and it comes back as a list, so the round trip is not exact. JSON keeps the data, not the Python types.
JSON Lines (.jsonl) stores one JSON object per line. You can append a record without rewriting the file, and read a huge file one line at a time. Logging systems, ML datasets and experiment trackers use it. Write it with json.dumps(record) + "\n"; read it with json.loads(line) in a loop.
pickle: save any Python object
Section titled “pickle: save any Python object”The pickle module serializes almost any Python object to bytes, and rebuilds it later: dicts with tuple keys, sets, dates, and objects of your own classes. ML libraries use it to save fitted models (module 34 uses joblib, which builds on pickle). A pickle is binary, so open the file with "wb" and "rb".
import picklefrom datetime import date
state = {"trained_on": date(2024, 12, 31), "classes": {0, 1}, "shape": (5000, 15)}with open("output/state.pkl", "wb") as f: pickle.dump(state, f)with open("output/state.pkl", "rb") as f: restored = pickle.load(f)print(restored == state, restored["trained_on"], sorted(restored["classes"]))True 2024-12-31 [0, 1]Pickles have two more limits. Other languages cannot read them. And a pickle of an object from a library may not load under another version of that library, so it suits short-lived caches and models you retrain, not long-term archives.
Choosing a format
Section titled “Choosing a format”| Format | Text or binary | Holds | Strengths | Weaknesses |
|---|---|---|---|---|
plain text (.txt, .log) |
text | lines | simple, readable, appendable | no structure; you parse it |
| CSV | text | one table | every tool reads it, Excel opens it | no types, quoting rules, one table only |
| JSON | text | nested data | types for numbers, booleans, null; APIs and configs | verbose for big tables; no dates |
| JSON Lines | text | one record per line | streamable, appendable | each line must be valid JSON |
| pickle | binary | any Python object | exact round trip of Python types | unsafe to load untrusted; Python only; version fragile |
| Parquet (module 24) | binary | typed tables | fast, compressed, keeps dtypes | needs a library such as pandas or Polars |
A practical rule: CSV to exchange tables with people, JSON for configs and API data, JSON Lines for logs and record streams, Parquet for large tables between pipeline steps, pickle only for your own short-lived Python objects.
Walking directories
Section titled “Walking directories”A pipeline often processes every file in a folder. pathlib has four ways to list files:
| Call | Finds | Example |
|---|---|---|
folder.iterdir() |
every entry directly in the folder | files and subfolders of data/ |
folder.glob("*.csv") |
entries that match a glob pattern | the CSV files directly in data/ |
folder.rglob("*.csv") |
matches in the folder and all subfolders (recursive) | every CSV under data/ |
folder.walk() |
one (dirpath, dirnames, filenames) per folder (Python 3.12+) |
an inventory of a tree |
A glob pattern uses * for “any characters”, ? for “one character” and [0-9] for “one character from this set”. "2024-0[1-3].csv" matches the first three monthly reports.
These calls return entries in the order the file system gives them, which differs between machines. Always sort the result before you process it, so runs are reproducible:
reports = sorted(Path("data/reports").glob("*.csv"))print([p.name for p in reports])print([p.name for p in sorted(Path("data/reports").glob("2024-0[1-3].csv"))])['2024-01.csv', '2024-02.csv', '2024-03.csv', '2024-04.csv', '2024-05.csv', '2024-06.csv']['2024-01.csv', '2024-02.csv', '2024-03.csv']Path.walk() visits a folder, then each subfolder. Sort dirnames in place to fix the visiting order. Real folders also hold hidden files, whose names start with a dot, such as the .DS_Store files that macOS Finder creates. Skip them, or your counts change from machine to machine:
for dirpath, dirnames, filenames in Path("data").walk(): dirnames.sort() visible = [name for name in filenames if not name.startswith(".")] size = sum((dirpath / name).stat().st_size for name in visible) print(f"{dirpath.as_posix():12} {len(visible):2} files {size:>9,} bytes")data 18 files 6,675,127 bytesdata/api 7 files 42,888 bytesdata/logs 1 files 50,124 bytesdata/reports 6 files 18,149 bytesos.walk("data") does the same with strings instead of Path objects, and works on older Python versions. dirpath / name builds the full path of each file.
File errors
Section titled “File errors”File operations fail for reasons outside your code: a file is missing, a name is a folder, a permission is denied. Each reason has its own exception. All of them are subclasses of OSError, so except OSError catches every one.
| Exception | Typical cause |
|---|---|
FileNotFoundError |
wrong path, or the script runs from another working directory |
FileExistsError |
mode "x", or mkdir() without exist_ok=True |
IsADirectoryError |
open() on a folder |
NotADirectoryError |
a path goes through a file as if it were a folder |
PermissionError |
no right to read or write; on Windows, a file that is open in Excel |
UnicodeDecodeError |
the file is not in the encoding you passed (a ValueError, not an OSError) |
json.JSONDecodeError |
the text is not valid JSON (also a ValueError) |
with open("data/sales_2025.csv", encoding="utf-8") as f: print(f.readline())FileNotFoundError: [Errno 2] No such file or directory: 'data/sales_2025.csv'When you see FileNotFoundError for a file that exists, check the working directory first: the terminal must be in the project folder.
Worked examples
Section titled “Worked examples”Example 1 — Clean a file of raw sensor readings
Section titled “Example 1 — Clean a file of raw sensor readings”Goal: data/readings.txt holds one temperature per line, but some lines are broken. Read it, keep the valid values, report what you skipped and write a clean file for the next pipeline step.
Step 1 — Check the file before you read it
Section titled “Step 1 — Check the file before you read it”from pathlib import Path
source = Path("data/readings.txt")print(source.name, source.suffix, source.is_file())print(source.stat().st_size, "bytes")readings.txt .txt True211 bytesA check before the work gives a clear message instead of a traceback later. The size tells you the file is tiny, so any reading method works.
Step 2 — Read the lines and sort them into valid and invalid
Section titled “Step 2 — Read the lines and sort them into valid and invalid”values = []skipped = []with open(source, encoding="utf-8") as f: for number, line in enumerate(f, start=1): text = line.strip() try: values.append(float(text)) except ValueError: skipped.append((number, text))print(len(values), "valid")print("skipped:", skipped)40 validskipped: [(12, 'error'), (24, ''), (35, 'n/a')]enumerate(f, start=1) numbers the lines from 1, as an editor does. strip() removes the \n and any spaces. float("") and float("n/a") raise a ValueError, so the except branch records the line number and the text.
Step 3 — Summarize the valid readings
Section titled “Step 3 — Summarize the valid readings”mean = sum(values) / len(values)print(f"min {min(values)} max {max(values)} mean {mean:.2f} °C")min 19.3 max 22.9 mean 21.06 °CThe summary uses only the 40 valid values. If you had turned the broken lines into 0, the mean would drop by about 1.5 °C, to 19.59 °C.
Step 4 — Write the clean values to the output folder
Section titled “Step 4 — Write the clean values to the output folder”out_dir = Path("output")out_dir.mkdir(parents=True, exist_ok=True)target = out_dir / "readings_clean.txt"with open(target, "w", encoding="utf-8") as f: for value in values: f.write(f"{value}\n")print("wrote", target.as_posix())wrote output/readings_clean.txtMode "w" creates the file or replaces an old version, so each run gives the same result. Each write() adds its own \n. The script prints the relative path, which is the same on every machine.
Step 5 — Read the clean file back to check it
Section titled “Step 5 — Read the clean file back to check it”check = target.read_text(encoding="utf-8").splitlines()print(len(check), check[:3], check[-1])print(all(19.0 <= float(line) <= 23.0 for line in check))40 ['21.0', '21.9', '21.4'] 21.1TrueReading your own output is a cheap test. 40 lines came out for 40 valid values, and every line converts back to a float.
Common mistakes:
- Forgetting
strip().float()accepts the trailing\n, but a comparison such astext == "error"fails, because the text is"error\n". - Converting broken lines to
0. That hides the problem and distorts the mean. Skip and report them. - Writing the clean file into
data/. Keep inputs read-only and write tooutput/.
Example 2 — Parse a CSV file correctly
Section titled “Example 2 — Parse a CSV file correctly”Goal: data/sales_raw.csv is a messy sales extract. Count its fields correctly, then build a margin table from data/products.csv and save it as a CSV for the finance team.
Step 1 — See why split(”,”) fails
Section titled “Step 1 — See why split(”,”) fails”lines = Path("data/sales_raw.csv").read_text(encoding="utf-8").splitlines()header = lines[0].split(",")broken = [line for line in lines[1:] if len(line.split(",")) != len(header)]print(len(header), "columns,", len(lines) - 1, "rows,", len(broken), "split wrongly")print(broken[0][:40])print(broken[0].split(",")[:3])13 columns, 1200 rows, 236 split wronglyO000096,"January 7, 2023",C00173,S03,Nor['O000096', '"January 7', ' 2023"']236 rows hold a quoted field with a comma inside, such as "January 7, 2023" or "$1,299.00". split(",") cuts these fields in two, so every later column shifts by one.
Step 2 — Parse the same file with csv.reader
Section titled “Step 2 — Parse the same file with csv.reader”import csv
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f: reader = csv.reader(f) header = next(reader) rows = list(reader)widths = {len(row) for row in rows}print(len(rows), "rows, field counts:", widths)print([row[:3] for row in rows if row[0] == "O000096"])1200 rows, field counts: {13}[['O000096', 'January 7, 2023', 'C00173']]Every row now has exactly 13 fields. The reader removed the quotes and kept January 7, 2023 as one value. next(reader) takes the header off before list(reader) reads the rest.
Step 3 — Read products by column name and convert the types
Section titled “Step 3 — Read products by column name and convert the types”with open("data/products.csv", encoding="utf-8", newline="") as f: products = list(csv.DictReader(f))p = products[0]print(p["product_id"], p["product"], repr(p["unit_price"]))margins = []for p in products: price = float(p["unit_price"]) cost = float(p["unit_cost"]) margins.append( { "product_id": p["product_id"], "product": p["product"], "category": p["category"], "margin_rate": round((price - cost) / price, 3), } )print(len(margins), margins[0]["product"], margins[0]["margin_rate"])P001 Wireless Earbuds '79.99'30 Wireless Earbuds 0.606DictReader gives each row as a dict keyed by the header, so the code says p["unit_price"] instead of p[4]. That stays correct if someone reorders the columns. The values are strings, so float() comes first.
Step 4 — Write the margin table with DictWriter
Section titled “Step 4 — Write the margin table with DictWriter”margins.sort(key=lambda row: row["margin_rate"], reverse=True)target = Path("output/product_margins.csv")with open(target, "w", encoding="utf-8", newline="") as f: columns = ["product_id", "product", "category", "margin_rate"] writer = csv.DictWriter(f, fieldnames=columns) writer.writeheader() writer.writerows(margins)print("wrote", len(margins), "rows to", target.as_posix())wrote 30 rows to output/product_margins.csvfieldnames fixes the column order of the output. writeheader() writes the names, and writerows() writes every dict. newline="" stops blank lines between rows on Windows.
Step 5 — Look at the result
Section titled “Step 5 — Look at the result”for line in target.read_text(encoding="utf-8").splitlines()[:4]: print(line)product_id,product,category,margin_rateP026,Vitamin C Face Serum,Beauty,0.748P030,Mineral Sunscreen SPF 50,Beauty,0.744P014,Running Socks 3-Pack,Clothing,0.72Two beauty products have the highest margins, followed by running socks. The file opens in Excel, pandas or any other tool.
Common mistakes:
- Parsing CSV with
split(","). It works on clean files and fails silently on the first quoted comma. Use thecsvmodule (or pandas, module 24). - Forgetting that every CSV value is a string.
"79.99" > "129.95"isTrue, because strings compare character by character. - Opening the CSV without
newline="". On Windows, the written file gets an empty line after every row.
Example 3 — Flatten nested customer records from JSON
Section titled “Example 3 — Flatten nested customer records from JSON”Goal: A CRM system exports data/customers.json: 20 customer records with a nested address and a list of orders. Turn it into a flat table with one row per order, ready for analysis.
Step 1 — Load the file and look at the top level
Section titled “Step 1 — Load the file and look at the top level”import json
with open("data/customers.json", encoding="utf-8") as f: export = json.load(f)print(type(export), list(export))print(export["count"], len(export["customers"]), export["exported_at"])<class 'dict'> ['exported_at', 'count', 'customers']20 20 2025-01-02T06:00:00Zjson.load() returns ordinary Python objects: here a dict with three keys. The count field matches the length of the list, a quick check that the export is complete.
Step 2 — Inspect one record
Section titled “Step 2 — Inspect one record”first = export["customers"][0]print(list(first)[:5])print(list(first)[5:])print(first["address"])print(first["tags"], len(first["orders"]))print(first["orders"][0])['customer_id', 'name', 'email', 'signup_date', 'plan']['address', 'tags', 'orders', 'phone']{'street': '546 Park Blvd', 'city': 'Chicago', 'region': 'North', 'postal_code': '81790'}['mobile_app', 'referral'] 5{'order_id': 'O000614', 'date': '2023-02-18', 'items': 1, 'amount': 32.0}A record nests a dict (address) and two lists (tags and orders). Each order is itself a dict. You reach a nested value by chaining keys and indexes: first["orders"][0]["amount"].
Step 3 — Handle fields that are missing or null
Section titled “Step 3 — Handle fields that are missing or null”customers = export["customers"]with_phone = [c["customer_id"] for c in customers if c.get("phone")]null_phone = [c["customer_id"] for c in customers if c.get("phone", "") is None]absent = [c["customer_id"] for c in customers if "phone" not in c]no_postal = [c["customer_id"] for c in customers if "postal_code" not in c["address"]]no_orders = [c["customer_id"] for c in customers if not c["orders"]]print("phone:", len(with_phone), " null:", null_phone, " absent:", len(absent))print("no postal code:", no_postal)print("no orders:", no_orders)phone: 6 null: ['C00010'] absent: 13no postal code: ['C00005', 'C00014']no orders: ['C00008', 'C00012', 'C00013']Real exports are uneven. A key can be absent ("phone" in c is False) or present with the value null (c["phone"] is None). c["phone"] raises a KeyError on an absent key, but c.get("phone") returns None for both cases.
Step 4 — Flatten the orders into rows
Section titled “Step 4 — Flatten the orders into rows”rows = []for c in customers: for order in c["orders"]: rows.append( { "customer_id": c["customer_id"], "plan": c["plan"], "city": c["address"]["city"], "postal_code": c["address"].get("postal_code", ""), "order_id": order["order_id"], "date": order["date"], "items": order["items"], "amount": order["amount"], } )print(len(rows), "order rows")print(list(rows[0]))print(list(rows[0].values()))48 order rows['customer_id', 'plan', 'city', 'postal_code', 'order_id', 'date', 'items', 'amount']['C00001', 'premium', 'Chicago', '81790', 'O000614', '2023-02-18', 1, 32.0]The outer loop walks the customers and the inner loop walks each customer’s orders. Every row copies the customer fields it needs, so the table is flat: one level, no nesting. Customers without orders produce no rows. .get("postal_code", "") gives an empty string for the two missing postal codes.
Step 5 — Save the table as CSV and a summary as JSON
Section titled “Step 5 — Save the table as CSV and a summary as JSON”with open("output/customer_orders.csv", "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(rows)
totals = {}for row in rows: totals[row["plan"]] = round(totals.get(row["plan"], 0) + row["amount"], 2)with open("output/revenue_by_plan.json", "w", encoding="utf-8") as f: json.dump(totals, f, indent=2, sort_keys=True)print(Path("output/revenue_by_plan.json").read_text(encoding="utf-8")){ "basic": 5629.3, "premium": 4187.06, "standard": 3895.34}The CSV holds the detail; the JSON holds a small summary for a dashboard. indent=2 makes the JSON readable, and sort_keys=True makes the key order fixed, so two runs give identical files that are easy to compare.
Common mistakes:
- Writing
c["phone"]for an optional field. It raisesKeyError: 'phone'on the first record without a phone. Usec.get("phone"). - Treating “absent” and
nullas different when the analysis does not care. Decide once, then use one rule. - Opening a JSON file and calling
f.read()thenjson.loads(). It works, butjson.load(f)is one call.
Example 4 — Drive a pipeline from a config file
Section titled “Example 4 — Drive a pipeline from a config file”Goal: data/config.json holds the settings of a sales pipeline: input paths, thresholds and model parameters. Load it, check it, and record each run in a JSON file and a JSON Lines log.
Step 1 — Load the config and read nested settings
Section titled “Step 1 — Load the config and read nested settings”with open("data/config.json", encoding="utf-8") as f: config = json.load(f)print(config["project"], config["version"])print(config["thresholds"]["max_quantity"], type(config["thresholds"]["max_discount"]))print(config["model"]["params"], config["output"]["overwrite"])sales-pipeline 1.4.050 <class 'float'>{'C': 1.0, 'max_iter': 1000} FalseJSON keeps the types: max_quantity is an int, max_discount a float and overwrite a bool. A CSV config would give you strings only. Changing a threshold now means editing the config, not the code.
Step 2 — Check that every input path exists
Section titled “Step 2 — Check that every input path exists”for name, raw_path in config["input"].items(): path = Path(raw_path) kind = "folder" if path.is_dir() else "file" if path.is_file() else "MISSING" print(f"{name:12} {path.as_posix():20} {kind}")sales data/sales.csv filecustomers data/customers.csv fileproducts data/products.csv filestores data/stores.csv filereports_dir data/reports folderThe paths in the config are relative, like every path in this course. Checking them all before the pipeline starts turns a crash halfway through into a clear message at the start. This pattern is called fail fast.
Step 3 — Read optional settings with defaults
Section titled “Step 3 — Read optional settings with defaults”export = config.get("export", {})compress = export.get("compress", False)level = config.get("logging", {}).get("level", "WARNING")print(compress, level)False INFOThe config has no export section, so .get("export", {}) returns an empty dict and the second .get() returns the default. The logging section exists, so its real value comes back. Older config files keep working when you add new settings.
Step 4 — Save the settings of this run
Section titled “Step 4 — Save the settings of this run”from datetime import date
run = { "run_id": "run-0010", "run_date": date(2024, 5, 2), "model": config["model"]["type"], "params": config["model"]["params"],}try: json.dumps(run)except TypeError as error: print("TypeError:", error)run["run_date"] = run["run_date"].isoformat()Path("output/run-0010.json").write_text(json.dumps(run, indent=2), encoding="utf-8")print(json.loads(Path("output/run-0010.json").read_text(encoding="utf-8")) == run)TypeError: Object of type date is not JSON serializableTrueJSON has no date type, so json.dumps() refuses a date. isoformat() turns the date into the text "2024-05-02", which every system reads. The final check shows that the file holds exactly the dict.
Step 5 — Append each run to a JSON Lines log
Section titled “Step 5 — Append each run to a JSON Lines log”runs_log = Path("output/runs.jsonl")runs_log.unlink(missing_ok=True) # start fresh: same output on every runfor run_id, auc in [("run-0010", 0.832), ("run-0011", 0.841)]: with open(runs_log, "a", encoding="utf-8") as f: f.write(json.dumps({"run_id": run_id, "roc_auc": auc}) + "\n")
with open(runs_log, encoding="utf-8") as f: history = [json.loads(line) for line in f]print(runs_log.read_text(encoding="utf-8"), end="")print(max(history, key=lambda r: r["roc_auc"])["run_id"]){"run_id": "run-0010", "roc_auc": 0.832}{"run_id": "run-0011", "roc_auc": 0.841}run-0011Mode "a" adds a line per run and never rewrites the old ones. Each line is a complete JSON object, so the reader parses line by line. unlink(missing_ok=True) deletes the file if it exists; a real pipeline would keep the history.
Common mistakes:
- Hard-coding values that belong in the config. When a threshold changes, you edit code, and old results become hard to reproduce.
- Storing dates as
dateobjects in JSON. Convert them withisoformat()and parse them back withdate.fromisoformat(). - Appending to a
.jsonfile. A file with two JSON objects in a row is not valid JSON. Use JSON Lines for logs.
Example 5 — Fix a legacy file encoding
Section titled “Example 5 — Fix a legacy file encoding”Goal: A procurement system exports its supplier list as data/legacy_latin1.csv. Reading it fails. Find out why, read it correctly and convert it to UTF-8 for the rest of the pipeline.
Step 1 — Try to read it as UTF-8
Section titled “Step 1 — Try to read it as UTF-8”text = Path("data/legacy_latin1.csv").read_text(encoding="utf-8")UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 49: invalid continuation byteThe error names the encoding, the byte (0xe9) and its position (49). In UTF-8, a character outside ASCII takes 2 to 4 bytes. The first byte, such as 0xe9, must be followed by continuation bytes: bytes from 0x80 to 0xbf that complete the character. Here a space follows it. So the file is not UTF-8.
Step 2 — Look at the bytes
Section titled “Step 2 — Look at the bytes”raw = Path("data/legacy_latin1.csv").read_bytes()print(len(raw), "bytes")print(raw[40:62])print(raw[49], hex(raw[49]))562 bytesb'SUP01,Caf\xe9 M\xfcller GmbH'233 0xe9Binary reading never fails, because it decodes nothing. Around position 49 you see Caf\xe9 M\xfcller. In Latin-1, 0xe9 is é and 0xfc is ü: each accented letter is one byte. This fits Latin-1, which the file name also suggests.
Step 3 — Read it with the right encoding
Section titled “Step 3 — Read it with the right encoding”with open("data/legacy_latin1.csv", encoding="latin-1", newline="") as f: suppliers = list(csv.DictReader(f))print(len(suppliers), "suppliers")for s in suppliers[:3]: print(s["supplier_id"], s["supplier"], s["city"], s["country"])12 suppliersSUP01 Café Müller GmbH Köln GermanySUP02 Textiles Señora Málaga SpainSUP03 Maison Lefèvre Besançon FranceWith encoding="latin-1", each byte becomes the right character. Latin-1 maps every byte from 0 to 255 to a character, so it never raises an error. That also means it never warns you when it is the wrong choice: always check the text.
Step 4 — See what the wrong guess looks like
Section titled “Step 4 — See what the wrong guess looks like”wrong = raw.decode("cp1252")utf8_bytes = "Café Müller".encode() # encode() uses UTF-8 by defaultprint(wrong.splitlines()[1])print(utf8_bytes.decode("latin-1"))SUP01,Café Müller GmbH,Köln,Germany,2015Café Müllercp1252 agrees with Latin-1 for these letters, so the first line is correct too. The second line is the reverse mistake: UTF-8 bytes read as Latin-1. Each accented letter turns into two odd characters. When you see é or ü in a report, a UTF-8 file was read with a one-byte encoding.
Step 5 — Save a UTF-8 copy
Section titled “Step 5 — Save a UTF-8 copy”target = Path("output/suppliers_utf8.csv")with open(target, "w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=list(suppliers[0])) writer.writeheader() writer.writerows(suppliers)print(target.as_posix(), target.stat().st_size, "bytes")print(target.read_text(encoding="utf-8").splitlines()[12])output/suppliers_utf8.csv 604 bytesSUP12,Ñandú Outdoor,Asunción,Paraguay,2023The UTF-8 copy has 42 more bytes than the original, for two reasons. Each of the 29 accented letters now takes 2 bytes instead of 1. And the csv writer ends each of the 13 lines with \r\n, the line ending of the CSV standard, where the source used \n (exercise M07-C12 measures both). The copy reads correctly as UTF-8. Convert legacy files once, at the start of the pipeline, and every later step can assume UTF-8.
Common mistakes:
- Using
errors="ignore"to make the error go away. It deletes the accented letters:Caf Mller. Find the real encoding instead. - Guessing the encoding from one file and applying it to all files from a source. Check each source once and record its encoding in the config.
- Writing the converted file without
encoding="utf-8". On an older Windows Python, the output is cp1252 again.
Example 6 — Save a fitted lookup model with pickle
Section titled “Example 6 — Save a fitted lookup model with pickle”Goal: Fit a very simple churn model, the churn rate per contract type in data/customers.csv, save it with its metadata, and load it in another script to score a new customer.
Step 1 — Fit the churn rate per contract
Section titled “Step 1 — Fit the churn rate per contract”counts = {}churned = {}with open("data/customers.csv", encoding="utf-8", newline="") as f: for row in csv.DictReader(f): contract = row["contract"] counts[contract] = counts.get(contract, 0) + 1 churned[contract] = churned.get(contract, 0) + int(row["churned"])rates = {c: round(churned[c] / counts[c], 3) for c in sorted(counts)}print(sum(counts.values()), "customers")print(rates)5000 customers{'month-to-month': 0.296, 'one-year': 0.088, 'two-year': 0.032}This “model” is a lookup table: the share of customers who churned, per contract type. It is a real baseline: month-to-month customers churn almost ten times as often as two-year customers.
Step 2 — Bundle the model with its metadata
Section titled “Step 2 — Bundle the model with its metadata”model = { "kind": "churn_rate_by_contract", "rates": rates, "classes": {0, 1}, "trained_on": date(2024, 12, 31), "n_rows": sum(counts.values()),}try: json.dumps(model)except TypeError as error: print("JSON:", error)JSON: Object of type set is not JSON serializableThe metadata uses a set and a date, which JSON cannot store. You could convert them by hand. pickle stores them as they are.
Step 3 — Save with pickle and load it back
Section titled “Step 3 — Save with pickle and load it back”import pickle
model_path = Path("output/churn_lookup.pkl")with open(model_path, "wb") as f: pickle.dump(model, f)
with open(model_path, "rb") as f: loaded = pickle.load(f)print(loaded == model, type(loaded["trained_on"]), loaded["classes"])new_contract = "month-to-month"print("churn risk for a new", new_contract, "customer:", loaded["rates"][new_contract])True <class 'datetime.date'> {0, 1}churn risk for a new month-to-month customer: 0.296"wb" and "rb" are required: a pickle is bytes, not text, so it takes no encoding. The loaded dict equals the original, with the same set and date types. A second script, run tomorrow, can load this file and score customers without refitting.
Step 4 — See why an untrusted pickle is dangerous
Section titled “Step 4 — See why an untrusted pickle is dangerous”class Payload: def __reduce__(self): return (print, ("This code ran inside pickle.loads()!",))
evil = pickle.dumps(Payload())result = pickle.loads(evil)print("pickle.loads returned:", result)This code ran inside pickle.loads()!pickle.loads returned: NoneThe method __reduce__ tells pickle how to rebuild an object: “call this function with these arguments”. Here the function is print, so loading the bytes prints a line. An attacker would write a function call that deletes files or sends your credentials. You do not need to understand classes yet (module 18); remember the lesson: loading a pickle runs code.
Common mistakes:
- Opening a pickle file in text mode.
pickle.dump()then raisesTypeError: write() argument must be str, not bytes. - Loading a model pickle that you downloaded from a stranger. Prefer formats that hold only data, or check the source.
- Using pickle as a long-term archive. After a library upgrade, an old pickle may not load. Keep the training code so you can refit.
Example 7 — Combine a folder of monthly reports
Section titled “Example 7 — Combine a folder of monthly reports”Goal: The finance team drops one CSV per month into data/reports/. The application log says that loading 2024-04.csv failed. Find the cause and combine the six files into one table that a dashboard can read.
Step 1 — List the monthly files
Section titled “Step 1 — List the monthly files”report_dir = Path("data/reports")files = sorted(report_dir.glob("2024-*.csv"))for path in files: print(path.as_posix(), path.stat().st_size, "bytes")data/reports/2024-01.csv 3014 bytesdata/reports/2024-02.csv 2902 bytesdata/reports/2024-03.csv 2890 bytesdata/reports/2024-04.csv 3146 bytesdata/reports/2024-05.csv 2874 bytesdata/reports/2024-06.csv 3323 bytesThe glob pattern selects the monthly files, and sorted() puts them in month order on every operating system. The file names are ISO dates, so text order is time order.
Step 2 — Compare the headers
Section titled “Step 2 — Compare the headers”expected = Nonefor path in files: with open(path, encoding="utf-8", newline="") as f: header = next(csv.reader(f)) if expected is None: expected = header status = "ok" if header == expected else "DIFFERENT ORDER" print(path.name, status)print(expected)with open(files[3], encoding="utf-8", newline="") as f: print(next(csv.reader(f)))2024-01.csv ok2024-02.csv ok2024-03.csv ok2024-04.csv DIFFERENT ORDER2024-05.csv ok2024-06.csv ok['order_id', 'order_date', 'store_id', 'product', 'category', 'quantity', 'revenue']['order_date', 'order_id', 'store_id', 'category', 'product', 'revenue', 'quantity']Each file has the same seven columns, but April lists them in another order. Same names, same count, different positions: the kind of difference that a quick look at the file misses.
Step 3 — See what naive concatenation does
Section titled “Step 3 — See what naive concatenation does”def revenue_by_position(path): with open(path, encoding="utf-8", newline="") as f: reader = csv.reader(f) next(reader) return round(sum(float(row[6]) for row in reader), 2)
def revenue_by_name(path): with open(path, encoding="utf-8", newline="") as f: return round(sum(float(row["revenue"]) for row in csv.DictReader(f)), 2)
print("by position:", revenue_by_position(files[3]))print("by name: ", revenue_by_name(files[3]))by position: 75.0by name: 10879.04Column 6 is revenue in five files but quantity in April. Code that works by position adds up the quantities and reports April revenue of 75 USD, which is really the number of units sold. Nothing crashes: the number is just wrong. Reading by header name gives the real 10,879.04.
Step 4 — Combine all files by column name
Section titled “Step 4 — Combine all files by column name”fieldnames = [ "month", "order_id", "order_date", "store_id", "product", "category", "quantity", "revenue",]combined = Path("output/reports_2024_h1.csv")rows_per_file = {}with open(combined, "w", encoding="utf-8", newline="") as out: writer = csv.DictWriter(out, fieldnames=fieldnames) writer.writeheader() for path in files: with open(path, encoding="utf-8", newline="") as f: reader = csv.DictReader(f) count = 0 for row in reader: row["month"] = path.stem writer.writerow(row) count += 1 rows_per_file[path.name] = countprint(list(rows_per_file.values()))print(combined.as_posix(), sum(rows_per_file.values()), "rows")[48, 48, 47, 52, 47, 55]output/reports_2024_h1.csv 297 rowsDictReader reads each row by name, whatever the order in the file. DictWriter writes the columns in the order of fieldnames, so the output has one consistent layout. The extra month column records where each row came from: a lineage column that helps you trace a bad value back to its source file.
Step 5 — Summarize the combined file
Section titled “Step 5 — Summarize the combined file”revenue = {}units = {}with open(combined, encoding="utf-8", newline="") as f: for row in csv.DictReader(f): month = row["month"] revenue[month] = revenue.get(month, 0) + float(row["revenue"]) units[month] = units.get(month, 0) + int(row["quantity"])for month in sorted(revenue): print(f"{month} {units[month]:3} units {revenue[month]:>10,.2f} USD")print(f"total {sum(units.values()):3} units {sum(revenue.values()):>10,.2f} USD")2024-01 65 units 14,162.33 USD2024-02 73 units 4,719.04 USD2024-03 65 units 12,296.72 USD2024-04 75 units 10,879.04 USD2024-05 65 units 6,675.86 USD2024-06 66 units 8,533.40 USDtotal 409 units 57,266.39 USDApril now shows its real revenue. The combined file is the single source for the dashboard, and its totals can be checked against each monthly file.
Common mistakes:
- Gluing files together line by line (or with
cat). Each header line ends up in the data, and a file with another column order corrupts its rows. - Processing files in the order
glob()returns. Sort first. - Writing the combined file into
data/reports/. The next run would read it as a seventh month.
Example 8 — Summarize an application log
Section titled “Example 8 — Summarize an application log”Goal: The pipeline and its API write data/logs/app.log. An on-call engineer wants a daily summary: how many lines per level, which errors happened, and the model score of each pipeline run.
Step 1 — Look at the first lines
Section titled “Step 1 — Look at the first lines”log_path = Path("data/logs/app.log")with open(log_path, encoding="utf-8") as f: for number, line in enumerate(f, start=1): print(line.rstrip()[:72]) if number == 3: break2024-05-01 08:04:01,354 INFO [api] 10.0.3.17 GET /api/v1/reports/2024-042024-05-01 08:04:17,625 DEBUG [cache] Cache hit ratio 0.782024-05-01 08:08:01,234 INFO [api] 10.0.3.17 GET /api/v1/products?page=3Each line has a date, a time with milliseconds, a log level (how serious the message is: DEBUG, INFO, WARNING or ERROR), a component in brackets and a message. The code prints the first 72 characters of each line to keep the output narrow. break stops after three lines, so the rest of the file is never read.
Step 2 — Count the lines per level
Section titled “Step 2 — Count the lines per level”levels = {}other = 0with open(log_path, encoding="utf-8") as f: for line in f: if not line[:4].isdigit(): other += 1 continue level = line.split(maxsplit=3)[2] levels[level] = levels.get(level, 0) + 1print(levels)print(other, "lines without a timestamp"){'INFO': 447, 'DEBUG': 13, 'WARNING': 25, 'ERROR': 7}8 lines without a timestampsplit(maxsplit=3) splits at the first three runs of spaces only, so the message stays in one piece and the level is item 2. Eight lines do not start with a year: they belong to Python tracebacks that the pipeline logged. Skipping them keeps the counts correct.
Step 3 — Collect the errors with their tracebacks
Section titled “Step 3 — Collect the errors with their tracebacks”errors = []with open(log_path, encoding="utf-8") as f: for line in f: line = line.rstrip("\n") if " ERROR " in line: errors.append([line]) elif not line[:4].isdigit() and errors: errors[-1].append(line)print(len(errors), "errors")for line in errors[2]: print(line)7 errors2024-05-01 10:53:56,110 ERROR [loader] Failed to parse data/reports/2024-04.csvTraceback (most recent call last): File "pipeline/loader.py", line 58, in load_report df = pd.read_csv(path, usecols=EXPECTED_COLUMNS)ValueError: Usecols do not match columns, columns expected but not found: ['quantity']A line without a timestamp continues the entry above it, so the loop adds it to the last error. The third error, printed here, shows the problem from Example 7: the loader failed on 2024-04.csv, the file with the different column order.
Step 4 — Extract the model score of each run
Section titled “Step 4 — Extract the model score of each run”scores = {}current_run = Nonewith open(log_path, encoding="utf-8") as f: for line in f: if "Starting pipeline" in line: current_run = line.split()[-2] elif "roc_auc=" in line and current_run is not None: scores[current_run] = float(line.rsplit("roc_auc=", 1)[1])print(len(scores), "runs")best = max(scores, key=scores.get)print("best:", best, scores[best], " worst:", min(scores.values()))9 runsbest: run-0005 0.844 worst: 0.812The log does not repeat the run id on the model line, so the loop remembers the most recent Starting pipeline run-... line. This state variable links later lines to their run. rsplit("roc_auc=", 1) splits once, from the right, and keeps the number after the marker.
Step 5 — Write the summary report
Section titled “Step 5 — Write the summary report”summary = Path("output/log_summary.txt")with open(summary, "w", encoding="utf-8") as f: print(f"Log summary for {log_path.as_posix()}", file=f) for level in ["DEBUG", "INFO", "WARNING", "ERROR"]: print(f"{level:8} {levels[level]:4}", file=f) print(f"Best run: {best} (roc_auc {scores[best]})", file=f) for entry in errors: clock = entry[0][11:19] message = entry[0].split(maxsplit=3)[3] print(clock, message, file=f)print(summary.read_text(encoding="utf-8"), end="")Log summary for data/logs/app.logDEBUG 13INFO 447WARNING 25ERROR 7Best run: run-0005 (roc_auc 0.844)10:37:08 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s10:53:55 [db] OperationalError: database is locked (attempt 1/3), retrying in 1s10:53:56 [loader] Failed to parse data/reports/2024-04.csv15:35:27 [loader] Failed to parse data/reports/2024-04.csv17:18:02 [api] 198.51.100.23 POST /api/v1/predict 500 1188ms user=priya.nair@example.com18:28:00 [api] 203.0.113.45 GET /api/v1/products?page=2 500 1334ms user=priya.nair@example.com19:34:34 [api] 10.0.3.17 GET /api/v1/products?page=2 500 974ms user=tom.becker@example.orgprint(..., file=f) writes to the file instead of the terminal and adds the line break. The report lists each error with its clock time and message; the full tracebacks stay in the log. Module 09 replaces the split() calls with regular expressions, and module 10 turns the loop into a lazy pipeline for multi-gigabyte logs.
Common mistakes:
- Reading a large log with
read()orreadlines(). A loop over the file object uses almost no memory. - Assuming every line has the same format. Traceback lines, blank lines and partial last lines break
split()[2]. Check the line first. - Searching for
"ERROR"without spaces. A message such as[validator] column ERROR_FLAG missingwould match. Compare the level field instead:line.split(maxsplit=3)[2] == "ERROR".
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Running the script from another folder | FileNotFoundError for a file that exists |
cd to the project folder, or build paths from Path(__file__).parent |
No encoding= argument |
Works on macOS, UnicodeDecodeError or mojibake on Windows |
Always pass encoding="utf-8" (or the file’s real encoding) |
Opening an existing result with "w" |
The old content is gone | Use "a" to add, or "x" to refuse to overwrite |
f.write(line) without "\n" |
All records end up on one line | f.write(line + "\n") or print(line, file=f) |
CSV opened without newline="" |
Blank line after every row on Windows | open(path, "w", encoding="utf-8", newline="") |
line.split(",") on a CSV |
Shifted columns on rows with quoted commas | csv.reader or csv.DictReader |
| Reading CSV columns by position | Wrong numbers when a file has another column order | csv.DictReader and column names |
| Doing math on CSV values | TypeError, or wrong string comparisons |
Convert with int() / float() first |
json.dump() with a date or set |
TypeError: Object of type date is not JSON serializable |
isoformat(), sorted(s) for a set, or default=str |
json.dumps() on data with float("nan") |
The file holds NaN, which other JSON tools reject |
Replace NaN with None, or pass allow_nan=False to fail early |
Two json.dump() calls into one file |
json.JSONDecodeError: Extra data when you read it |
One object per file, or JSON Lines |
| A pickle opened in text mode | TypeError: write() argument must be str, not bytes |
"wb" and "rb" |
pickle.load() on a downloaded file |
Arbitrary code runs | Load only pickles you created; exchange data as JSON, CSV or Parquet |
Excel CSV with a BOM read as "utf-8" |
First column is '\ufeffstore_id' |
encoding="utf-8-sig" |
Processing glob() results unsorted |
Different order, and different results, on another machine | sorted(folder.glob("*.csv")) |
Writing results into data/ |
Inputs overwritten; the next run reads its own output | Write to output/, created with mkdir(parents=True, exist_ok=True) |
Using a file after the with block |
ValueError: I/O operation on closed file. |
Do the work inside the block, or keep the data in a variable |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Web development: web frameworks read JSON request bodies and settings files, serve static files with
pathlib, and let users download CSV exports written withcsv.DictWriter. - Automation: a script sorts a downloads folder with
rglob(), renames invoices withPath.rename(), and converts old Latin-1 exports to UTF-8 for a new system. - DevOps and tooling: engineers summarize server logs line by line, append audit records as JSON Lines, and keep tool settings in JSON or TOML files.
- Caching: build tools and test runners cache results to disk with pickle or JSON, so the second run is fast. Because of the pickle risk, they only load caches they wrote themselves.
Summary
Section titled “Summary”- A path is relative to the working directory. Use
pathlib.Path, join parts with/, and sort the results ofglob()andrglob(). - Write results to
output/, created withmkdir(parents=True, exist_ok=True). Keepdata/read-only. Print relative paths, withas_posix()where the text matters. with open(...) as f:closes the file for you, even after an error. A loop overfreads one line at a time.- Modes:
"r"reads,"w"replaces,"a"appends,"x"refuses to overwrite. Add"b"for bytes. - Text mode decodes bytes with an encoding. Always pass
encoding=. Write UTF-8; read legacy files with their real encoding; use"utf-8-sig"for Excel CSVs with a BOM. - Use the
csvmodule, notsplit(","). Open CSV files withnewline="".DictReaderandDictWriterwork by column name, which survives a change in column order. Every CSV value is a string. json.load/json.dumpread and write nested data with real types. JSON has no dates, sets or tuples. JSON Lines holds one record per line.picklesaves any Python object exactly, but loading a pickle runs code. Load only pickles you created.
Self-check questions
Section titled “Self-check questions”Q1. Your script opens data/sales.csv and fails with FileNotFoundError, but the file exists. What is the most likely cause?
Answer
The working directory is not the project folder. A relative path starts at the folder the terminal is in when you run python. cd to the project folder that contains data/, then run the script again.
Q2. What do Path("data/reports/2024-04.csv").stem, .suffix and .parent return?
Answer
'2024-04', '.csv' and Path('data/reports'). The stem is the name without the suffix; the parent is the folder that contains the file.
Q3. Why is with open(...) as f: better than f = open(...) followed by f.close()?
Answer
with closes the file when the block ends, even if an error happens inside it. With a manual close(), an error before that line leaves the file open, and written data may never reach the disk.
Q4. You open an existing results file with mode "w" and then the script crashes before it writes anything. What is in the file?
Answer
Nothing. Mode "w" empties the file as soon as it opens it. Use "a" to add to a file, or "x" to create a new file and refuse to overwrite an existing one.
Q5. A CSV row is O000096,"January 7, 2023",C00173. How many fields does split(",") give, and how many does csv.reader give?
Answer
split(",") gives 4 fields, because it also splits the comma inside the quoted date. csv.reader gives 3: O000096, January 7, 2023 and C00173, with the quotes removed.
Q6. Reading a file fails with UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9. What does it mean and what do you do?
Answer
The file is not UTF-8. 0xe9 is é in Latin-1 and cp1252, a common legacy encoding. Look at the bytes with read_bytes(), ask the source system if you can, then open the file with encoding="latin-1" (or "cp1252") and convert it to UTF-8.
Q7. What does json.loads(json.dumps({"shape": (5000, 15), 1: "a"})) return, and why does it differ from the input?
Answer
{'shape': [5000, 15], '1': 'a'}. JSON has arrays but no tuples, so the tuple comes back as a list. JSON object keys must be strings, so the key 1 becomes '1'.
Q8. A colleague emails you model.pkl and asks you to “just load it”. What is the risk, and what would you suggest?
Answer
pickle.load() can run any code that the file’s author chose, so loading the file could damage your machine or leak data. Load only pickles from a source you trust, such as your own pipeline. Ask for the training code, or for the model in a format that holds only data.
Q9. Why should you sort the result of Path("data/reports").glob("*.csv") before you process the files?
Answer
glob() returns files in the order the file system gives them, which differs between operating systems and machines. Sorting gives the same order everywhere, so the results, the output files and the logs are reproducible.
Q10. Why does combining the monthly reports with csv.DictReader give the right April revenue, when reading row[6] does not?
Answer
2024-04.csv has the same columns in a different order. row[6] is quantity in that file, not revenue. DictReader maps each value to its header name, so row["revenue"] is correct in every file.
Q11. When would you choose JSON Lines over a single JSON file?
Answer
When records arrive one at a time or the file is large: logs, experiment runs, event streams, training examples. You can append a line without rewriting the file, and read it line by line. A single JSON file must be read and written as a whole.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 28 exercises with hints and full solutions, from path basics to a full folder pipeline.
- Mini-project: build a config-driven script that turns the monthly report folder into summary files.
- Cheat sheet: paths, modes, encodings, CSV, JSON, pickle and directory walking on one page.
- Next module: 08. Modules, packages and environments turns your scripts into importable modules, a package and a command-line tool.