Skip to content

07. Files and data formats — Exercises

These exercises practice every idea of the Files and data formats lesson. They read the real course files in data/: the sensor readings, the stores, products and customers, the pipeline config, the legacy supplier list, the monthly reports and the application log.

How to work:

  1. Read the task and the expected output.
  2. Copy the starter code into a script (for example exercise.py) in your project folder, next to data/. Replace each to-do comment with your code.
  3. Run the script with python exercise.py from the project folder. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Two rules hold for every exercise. Read from data/ only, and write every result to output/, created with Path("output").mkdir(parents=True, exist_ok=True). Never write into data/.

Warm-up

The April report lives at data/reports/2024-04.csv. Build the path with pathlib and print its name, stem, suffix and parent. Then print two derived paths: the same folder with the name 2024-04_clean.csv, and the same name with the suffix .json.

Expected output
name: 2024-04.csv
stem: 2024-04
suffix: .csv
parent: data/reports
data/reports/2024-04_clean.csv
data/reports/2024-04.json
Starter
from pathlib import Path
report = Path("data") / "reports" / "2024-04.csv"
# TODO: print name, stem, suffix and parent on one line each
# TODO: print the path with the new name, then the path with the .json suffix
Hint 1

The attributes are .name, .stem, .suffix and .parent. They are attributes, not methods: no parentheses.

Hint 2

report.with_name("2024-04_clean.csv") and report.with_suffix(".json") return new paths. Print them with .as_posix() so the output is the same on Windows.

Solution
from pathlib import Path
report = Path("data") / "reports" / "2024-04.csv"
print("name: ", report.name)
print("stem: ", report.stem)
print("suffix:", report.suffix)
print("parent:", report.parent.as_posix())
clean = report.with_name("2024-04_clean.csv")
as_json = report.with_suffix(".json")
print(clean.as_posix())
print(as_json.as_posix())
assert report.stem + report.suffix == report.name
assert clean.parent == report.parent
assert as_json.stem == report.stem
Output
name: 2024-04.csv
stem: 2024-04
suffix: .csv
parent: data/reports
data/reports/2024-04_clean.csv
data/reports/2024-04.json

How it works:

  1. The / operator joins the three parts into one Path.
  2. name is the last part. stem drops the suffix, and suffix keeps the dot.
  3. with_name() replaces the whole last part; with_suffix() replaces only the extension. Both return new paths and leave report unchanged.
  4. Neither call touches the disk. The new files do not exist until you write them.

Alternative: report.parent / f"{report.stem}_clean{report.suffix}" builds the clean name from its parts. This form helps when you add a tag to many file names in a loop.

Warm-up

Open data/readings.txt with with open(...) and loop over the file. Count all lines and the lines that are empty after strip().

Expected output
lines: 43
empty: 1
Starter
total = 0
empty = 0
# TODO: open data/readings.txt with encoding="utf-8" and loop over the lines
# TODO: print the two counts
Hint 1

for line in f: gives each line with its \n. line.strip() is "" for an empty line.

Hint 2

An empty string is falsy, so if not line.strip(): finds the empty lines.

Solution
total = 0
empty = 0
with open("data/readings.txt", encoding="utf-8") as f:
for line in f:
total += 1
if not line.strip():
empty += 1
print("lines:", total)
print("empty:", empty)
assert total == 43
assert empty == 1
Output
lines: 43
empty: 1

How it works:

  1. with opens the file and closes it after the loop.
  2. Each pass of the loop reads one line, so the file is never in memory as a whole.
  3. The empty line 24 is the only line whose stripped text is "".

Alternative: for a small file, Path("data/readings.txt").read_text(encoding="utf-8").splitlines() gives a list of lines; len() counts them. It reads the whole file at once, so keep the loop for large files.

Warm-up

Predict the output: the code below opens the same file four times with different modes. Write down the text that the last line prints. Then run the code.

Acceptance criteria:

  • Write your prediction line by line, then run the code.
  • Your prediction matches the Output in the solution, including which lines survive.
Starter
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
path = Path("output/modes.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("run 1\n")
with open(path, "a", encoding="utf-8") as f:
f.write("run 2\n")
with open(path, "w", encoding="utf-8") as f:
f.write("run 3\n")
with open(path, "a", encoding="utf-8") as f:
f.write("run 4\n")
print(repr(path.read_text(encoding="utf-8")))
# TODO: write your prediction before you run the code
Hint 1

"w" empties the file when it opens it. "a" keeps what is there and writes at the end.

Hint 2

Only the writes after the last "w" survive.

Solution
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
path = Path("output/modes.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("run 1\n")
with open(path, "a", encoding="utf-8") as f:
f.write("run 2\n")
with open(path, "w", encoding="utf-8") as f:
f.write("run 3\n")
with open(path, "a", encoding="utf-8") as f:
f.write("run 4\n")
print(repr(path.read_text(encoding="utf-8")))
assert path.read_text(encoding="utf-8").splitlines() == ["run 3", "run 4"]
Output
'run 3\nrun 4\n'

How it works:

  1. The first "w" creates the file with run 1. The "a" adds run 2.
  2. The second "w" erases both lines before it writes run 3.
  3. The last "a" adds run 4 after run 3.
  4. repr() shows the \n characters, so you can see that each line ends with a line break.

Alternative: to keep every run, open the file once with "a" for each run. To protect a file from being replaced, open it with "x": the third open() would then raise FileExistsError.

M07-W04 · Fix the bug: write() needs text

Section titled “M07-W04 · Fix the bug: write() needs text”
Warm-up

Fix the bug: this code should save the number of valid readings to output/count.txt, but it crashes.

from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
valid_count = 40
with open("output/count.txt", "w", encoding="utf-8") as f:
f.write(valid_count)
Output
TypeError: write() argument must be str, not int

Fix the write() line so that the file holds valid_readings=40 and a line break, then print the file content with repr():

Expected output
'valid_readings=40\n'
Starter
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
valid_count = 40
with open("output/count.txt", "w", encoding="utf-8") as f:
f.write(valid_count) # TODO: fix this line
# TODO: print the file content with repr()
Hint 1

Read the last line of the error. A text file accepts only str.

Hint 2

Build the line with an f-string and add "\n" yourself: write() adds no line break.

Solution
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
valid_count = 40
with open("output/count.txt", "w", encoding="utf-8") as f:
f.write(f"valid_readings={valid_count}\n")
content = Path("output/count.txt").read_text(encoding="utf-8")
print(repr(content))
assert content == "valid_readings=40\n"
Output
'valid_readings=40\n'

How it works:

  1. A file opened in text mode needs a str. write(40) raises TypeError, because Python does not convert numbers for you.
  2. The f-string turns the number into text and adds the label.
  3. The "\n" ends the line, so another value appended later starts on a new line.

Alternative: print(f"valid_readings={valid_count}", file=f) converts and adds the line break for you.

Warm-up

Use csv.reader to read data/stores.csv. Print the header row, then count the data rows.

Expected output
['store_id', 'city', 'region', 'size_sqm', 'opened']
12 stores
Starter
import csv
with open("data/stores.csv", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
# TODO: take the header with next(), then count the remaining rows
# TODO: print the header and the count
Hint 1

next(reader) returns the first row, which is the header. The reader then continues from the second row.

Hint 2

sum(1 for row in reader) or len(list(reader)) counts the rest. Do it inside the with block, while the file is open.

Solution
import csv
with open("data/stores.csv", encoding="utf-8", newline="") as f:
reader = csv.reader(f)
header = next(reader)
row_count = len(list(reader))
print(header)
print(row_count, "stores")
assert header[0] == "store_id"
assert row_count == 12
Output
['store_id', 'city', 'region', 'size_sqm', 'opened']
12 stores

How it works:

  1. csv.reader gives each row as a list of strings.
  2. next(reader) consumes the header, so list(reader) holds only the 12 store rows.
  3. Both calls are inside the with block. After the block, the file is closed and the reader cannot read any more.

Alternative: csv.DictReader(f).fieldnames gives the header without a separate next() call.

Warm-up

Load data/config.json with json.load(). Print the project and version, the reports folder, the retry back-off list and the Python type of thresholds.

Expected output
sales-pipeline 1.4.0
data/reports/
[1, 2, 4]
<class 'dict'>
Starter
import json
# TODO: open data/config.json and load it into config
# TODO: print the four lines
Hint 1

json.load(f) takes an open file. The result is a dict.

Hint 2

Nested values need two keys: config["input"]["reports_dir"], config["retry"]["backoff_seconds"].

Solution
import json
with open("data/config.json", encoding="utf-8") as f:
config = json.load(f)
print(config["project"], config["version"])
print(config["input"]["reports_dir"])
print(config["retry"]["backoff_seconds"])
print(type(config["thresholds"]))
assert config["version"] == "1.4.0"
assert config["retry"]["backoff_seconds"] == [1, 2, 4]
Output
sales-pipeline 1.4.0
data/reports/
[1, 2, 4]
<class 'dict'>

How it works:

  1. json.load() turns the JSON object into a dict, the array into a list and the numbers into int values.
  2. Two keys in a row walk one level down the nesting.
  3. thresholds is a JSON object, so it becomes a dict.

Alternative: json.loads(Path("data/config.json").read_text(encoding="utf-8")) reads the text first and parses it second. It gives the same dict.

M07-W07 · Predict the output: a JSON round trip

Section titled “M07-W07 · Predict the output: a JSON round trip”
Warm-up

Predict the output: this code turns a dict into JSON text and back. Write down the two printed lines, then run the code. Watch the key 1, the None and the tuple.

Acceptance criteria:

  • Write your prediction for both lines, then run the code.
  • Your prediction matches the Output in the solution, including the quotes and brackets.
Starter
import json
record = {"store": "S01", 1: True, "missing": None, "limits": (19.0, 23.0)}
text = json.dumps(record)
print(text)
print(json.loads(text))
# TODO: write your prediction before you run the code
Hint 1

JSON writes true, null and arrays in square brackets. JSON object keys are always strings.

Hint 2

On the way back, null becomes None and an array becomes a list, not a tuple.

Solution
import json
record = {"store": "S01", 1: True, "missing": None, "limits": (19.0, 23.0)}
text = json.dumps(record)
print(text)
print(json.loads(text))
back = json.loads(text)
assert back["1"] is True
assert back["limits"] == [19.0, 23.0]
assert back != record
Output
{"store": "S01", "1": true, "missing": null, "limits": [19.0, 23.0]}
{'store': 'S01', '1': True, 'missing': None, 'limits': [19.0, 23.0]}

How it works:

  1. json.dumps() writes True as true, None as null and the tuple as an array [19.0, 23.0].
  2. The int key 1 becomes the string "1", because JSON keys must be strings.
  3. json.loads() gives a dict with the key '1' and a list instead of the tuple, so the result is not equal to the original.

Alternative: when exact Python types matter, convert them on load yourself (tuple(back["limits"])), or use pickle for your own short-lived files.

Warm-up

The supplier city Zürich must go into two systems: one stores UTF-8, the other Latin-1. Encode the name both ways, print the bytes and their lengths, and decode each back.

Expected output
b'Z\xc3\xbcrich' 7
b'Z\xfcrich' 6
Zürich Zürich 6
Starter
city = "Zürich"
# TODO: encode with "utf-8" and "latin-1"
# TODO: print each bytes value with its length, then the decoded text
Hint 1

city.encode("latin-1") returns a bytes object. len() of a bytes object counts bytes, not characters.

Hint 2

Decode with the same encoding you used to encode: data.decode("latin-1").

Solution
city = "Zürich"
as_utf8 = city.encode("utf-8")
as_latin1 = city.encode("latin-1")
print(as_utf8, len(as_utf8))
print(as_latin1, len(as_latin1))
print(as_utf8.decode("utf-8"), as_latin1.decode("latin-1"), len(city))
assert len(as_utf8) == len(as_latin1) + 1
assert as_latin1.decode("latin-1") == city
Output
b'Z\xc3\xbcrich' 7
b'Z\xfcrich' 6
Zürich Zürich 6

How it works:

  1. ü takes two bytes in UTF-8 (\xc3\xbc) and one byte in Latin-1 (\xfc). The other letters are ASCII and take one byte each.
  2. So the same 6 characters take 7 bytes in UTF-8 and 6 in Latin-1.
  3. Decoding with the matching encoding gives back the original text.

Alternative: as_utf8.decode("latin-1") shows what goes wrong with a mismatch: Zürich, the mojibake you see when a system guesses the wrong encoding.

Warm-up

The folder data/api/ holds saved API responses. List its .json files in sorted order, with one name per line, and print how many there are.

Expected output
error_429.json
products_page_1.json
products_page_2.json
products_page_3.json
users.json
weather_forecast.json
6 JSON files
Starter
from pathlib import Path
api_dir = Path("data/api")
# TODO: find the .json files with glob(), sort them, print each name and the count
Hint 1

api_dir.glob("*.json") finds the files whose name ends in .json.

Hint 2

Wrap the result in sorted(), then print path.name for each path.

Solution
from pathlib import Path
api_dir = Path("data/api")
json_files = sorted(api_dir.glob("*.json"))
for path in json_files:
print(path.name)
print(len(json_files), "JSON files")
assert all(p.suffix == ".json" for p in json_files)
assert len(json_files) == 6
Output
error_429.json
products_page_1.json
products_page_2.json
products_page_3.json
users.json
weather_forecast.json
6 JSON files

How it works:

  1. glob("*.json") matches names that end in .json. It skips catalog.html.
  2. sorted() gives the same order on every machine.
  3. path.name prints the file name without the folder.

Alternative: [p for p in sorted(api_dir.iterdir()) if p.suffix == ".json"] lists every entry and filters by suffix. Use it when the rule is more complex than a glob pattern.

M07-C01 · Clean the readings into a Fahrenheit file

Section titled “M07-C01 · Clean the readings into a Fahrenheit file”
Core

Read data/readings.txt. Skip lines that are not numbers. Write each valid reading, converted to Fahrenheit with 1 decimal, to output/readings_f.txt, one per line. Print the counts and the first three lines of the new file.

Expected output
valid: 40 invalid: 3
['69.8', '71.4', '70.5']
Starter
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
valid = 0
invalid = 0
# TODO: open the input for reading and output/readings_f.txt for writing
# TODO: for each line: try float(), convert to °F, write f"{value:.1f}\n"
# TODO: print the counts and the first three lines of the output file
Hint 1

One with statement can open two files: with open(a, encoding="utf-8") as src, open(b, "w", encoding="utf-8") as dst:.

Hint 2

Put the float() call in try, and count the line as invalid in except ValueError.

Hint 3

°F = °C × 9 / 5 + 32. Read the result with read_text().splitlines()[:3].

Solution
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
target = Path("output/readings_f.txt")
valid = 0
invalid = 0
with (
open("data/readings.txt", encoding="utf-8") as src,
open(target, "w", encoding="utf-8") as dst,
):
for line in src:
try:
celsius = float(line)
except ValueError:
invalid += 1
continue
dst.write(f"{celsius * 9 / 5 + 32:.1f}\n")
valid += 1
lines = target.read_text(encoding="utf-8").splitlines()
print("valid:", valid, "invalid:", invalid)
print(lines[:3])
assert valid == 40 and invalid == 3
assert len(lines) == valid
Output
valid: 40 invalid: 3
['69.8', '71.4', '70.5']

How it works:

  1. The parenthesized with (Python 3.10+) opens both files and closes both at the end.
  2. float(line) ignores the \n and the surrounding spaces. error, the empty line and n/a raise ValueError, so continue skips them.
  3. f"{...:.1f}\n" writes one rounded value per line.
  4. The asserts check the counts and that the file has one line per valid value.

Alternative: collect the values in a list first, then write them with target.write_text("".join(f"{v:.1f}\n" for v in fahrenheit), encoding="utf-8"). One write call is simple for small files; the streaming version above also works for huge files.

Core

Read data/stores.csv with csv.DictReader. For each region, count the stores and add up size_sqm. Print the regions in alphabetical order.

Expected output
East 3 stores 7,210 m²
North 3 stores 6,220 m²
South 3 stores 7,080 m²
West 3 stores 5,720 m²
Starter
import csv
stores = {}
area = {}
# TODO: read the file with DictReader and fill both dicts by region
# TODO: print one line per region, sorted
Hint 1

row["region"] is the key. stores.get(region, 0) + 1 counts without a KeyError.

Hint 2

row["size_sqm"] is a string. Convert it with int() before you add it.

Solution
import csv
stores = {}
area = {}
with open("data/stores.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
region = row["region"]
stores[region] = stores.get(region, 0) + 1
area[region] = area.get(region, 0) + int(row["size_sqm"])
for region in sorted(stores):
print(f"{region:6} {stores[region]} stores {area[region]:>6,} m²")
assert sum(stores.values()) == 12
assert area["North"] == 2850 + 1950 + 1420
Output
East 3 stores 7,210 m²
North 3 stores 6,220 m²
South 3 stores 7,080 m²
West 3 stores 5,720 m²

How it works:

  1. DictReader gives each row as a dict, so the code names the columns it uses.
  2. Two dicts collect the count and the sum per region.
  3. int() converts the area. Without it, + would raise TypeError because the value is text.
  4. :>6, right-aligns the number in 6 characters with a thousands separator.

Alternative: module 09 shows collections.Counter and defaultdict, which remove the .get(..., 0) calls. pandas does the whole task in one line: df.groupby("region")["size_sqm"].agg(["count", "sum"]) (module 25).

M07-C03 · Fix the bug: count orders per channel

Section titled “M07-C03 · Fix the bug: count orders per channel”
Core

Fix the bug: this code counts the rows of data/sales_raw.csv per sales channel. It runs, but the counts contain values that are not channels.

from pathlib import Path
counts = {}
lines = Path("data/sales_raw.csv").read_text(encoding="utf-8").splitlines()
for line in lines[1:]:
channel = line.split(",")[5]
counts[channel] = counts.get(channel, 0) + 1
print(sorted(counts.items(), key=lambda item: -item[1])[:4])
Output
[('store', 570), ('online', 416), ('South', 41), ('North', 40)]

Rewrite it with the csv module and the column name channel. Print the counts in sorted order of the channel value:

Expected output
'' 4
'-' 4
'N/A' 9
'online' 507
'store' 676
Starter
import csv
counts = {}
# TODO: read data/sales_raw.csv with csv.DictReader
# TODO: count row["channel"] and print the counts sorted by channel
Hint 1

Look at the wrong keys. North and South are regions: on some rows, the columns shifted by one.

Hint 2

Rows with a quoted date such as "January 7, 2023" contain an extra comma. csv.DictReader handles quoting.

Solution
import csv
counts = {}
with open("data/sales_raw.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
channel = row["channel"]
counts[channel] = counts.get(channel, 0) + 1
for channel in sorted(counts):
print(repr(channel), counts[channel])
assert sum(counts.values()) == 1200
assert set(counts) <= {"store", "online", "", "N/A", "-"}
Output
'' 4
'-' 4
'N/A' 9
'online' 507
'store' 676

How it works:

  1. 201 dates are written as "January 7, 2023", with a comma inside quotes. split(",") cuts them in two, so [5] points at the region column on those rows.
  2. csv.DictReader keeps a quoted field in one piece and maps every value to its column name.
  3. Now every value is a real channel or one of the missing-value tokens of this messy file ("", N/A, -). repr() makes the empty string visible.
  4. Module 26 cleans these tokens. Here, seeing them is the goal.

Alternative: csv.reader with row[5] also works, because the reader splits correctly. Use the column name anyway: it stays right if the export changes its column order.

M07-C04 · Write a high-margin product list

Section titled “M07-C04 · Write a high-margin product list”
Core

From data/products.csv, select the products with a margin rate of at least 0.70, where margin rate = (price − cost) / price. Write them to output/high_margin.csv with the columns product_id, product, margin_rate (3 decimals), sorted from the highest margin. Read the file back and print it.

Expected output
product_id,product,margin_rate
P026,Vitamin C Face Serum,0.748
P030,Mineral Sunscreen SPF 50,0.744
P014,Running Socks 3-Pack,0.72
P027,Hydrating Face Cream,0.716
Starter
import csv
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
selected = []
# TODO: read products.csv, compute the margin rate, keep rates >= 0.70
# TODO: sort, write with DictWriter (newline=""), then print the file
Hint 1

Convert unit_price and unit_cost with float(). Round the rate with round(rate, 3).

Hint 2

selected.sort(key=lambda r: r["margin_rate"], reverse=True) sorts the dicts. DictWriter(f, fieldnames=[...]) writes only those keys.

Solution
import csv
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
selected = []
with open("data/products.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
price = float(row["unit_price"])
rate = (price - float(row["unit_cost"])) / price
if rate >= 0.70:
selected.append(
{"product_id": row["product_id"], "product": row["product"],
"margin_rate": round(rate, 3)}
)
selected.sort(key=lambda r: r["margin_rate"], reverse=True)
target = Path("output/high_margin.csv")
with open(target, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["product_id", "product", "margin_rate"])
writer.writeheader()
writer.writerows(selected)
print(target.read_text(encoding="utf-8"), end="")
with open(target, encoding="utf-8", newline="") as f:
back = list(csv.DictReader(f))
assert len(back) == len(selected)
assert all(float(r["margin_rate"]) >= 0.70 for r in back)
Output
product_id,product,margin_rate
P026,Vitamin C Face Serum,0.748
P030,Mineral Sunscreen SPF 50,0.744
P014,Running Socks 3-Pack,0.72
P027,Hydrating Face Cream,0.716

How it works:

  1. The loop converts the two prices and computes the rate for each product.
  2. Only rows with a rate of at least 0.70 go into selected, as new dicts with the three output columns.
  3. DictWriter writes the header and the rows in the order of fieldnames.
  4. The asserts read the file back. The rates come back as strings, so the check converts them with float().

Alternative: if the output dict had extra keys, DictWriter(..., extrasaction="ignore") would skip them instead of raising ValueError. That lets you write a subset of the columns of a wider dict.

M07-C05 · Summarize customers from nested JSON

Section titled “M07-C05 · Summarize customers from nested JSON”
Core

Load data/customers.json. Count the customers per plan, the total number of orders, the customers with no orders and the total order amount.

Expected output
{'basic': 7, 'premium': 6, 'standard': 7}
orders: 48
no orders: ['C00008', 'C00012', 'C00013']
total amount: 13,711.70 USD
Starter
import json
# TODO: load the file and take the "customers" list
# TODO: count plans in a dict, add up len(c["orders"]) and the amounts
# TODO: print the four results
Hint 1

Each customer has an orders list. len(c["orders"]) counts its orders, and not c["orders"] is True for an empty list.

Hint 2

The amount is inside each order: loop over c["orders"] and add order["amount"].

Solution
import json
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
plans = {}
n_orders = 0
amount = 0.0
without = []
for c in customers:
plans[c["plan"]] = plans.get(c["plan"], 0) + 1
n_orders += len(c["orders"])
if not c["orders"]:
without.append(c["customer_id"])
for order in c["orders"]:
amount += order["amount"]
print(dict(sorted(plans.items())))
print("orders:", n_orders)
print("no orders:", without)
print(f"total amount: {amount:,.2f} USD")
assert sum(plans.values()) == 20
assert n_orders == 48
Output
{'basic': 7, 'premium': 6, 'standard': 7}
orders: 48
no orders: ['C00008', 'C00012', 'C00013']
total amount: 13,711.70 USD

How it works:

  1. json.load(f)["customers"] loads the file and keeps only the list of records.
  2. One loop over the customers fills the plan counts, the order count and the list of customers without orders.
  3. An inner loop adds the amount of each order.
  4. dict(sorted(plans.items())) prints the plans in alphabetical order.

Alternative: sum(len(c["orders"]) for c in customers) and sum(o["amount"] for c in customers for o in c["orders"]) compute the totals in one line each. The nested generator reads like the two nested loops.

M07-C06 · Fix the bug: KeyError on an optional field

Section titled “M07-C06 · Fix the bug: KeyError on an optional field”
Core

Fix the bug: this code prints the postal code of each customer in data/customers.json. It crashes on the fifth customer.

import json
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
for c in customers[:6]:
print(c["customer_id"], c["address"]["postal_code"])
Output
C00001 81790
C00002 62260
C00003 45915
C00004 78449
KeyError: 'postal_code'

Make it print unknown for a missing postal code, and print every customer whose postal code is missing:

Expected output
C00001 81790
C00002 62260
C00003 45915
C00004 78449
C00005 unknown
C00006 48100
missing: ['C00005', 'C00014']
Starter
import json
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
for c in customers[:6]:
print(c["customer_id"], c["address"]["postal_code"]) # TODO: fix this line
# TODO: print the ids of all customers without a postal code
Hint 1

The last line of the error names the missing key. Not every address has it.

Hint 2

d.get(key, default) returns the default when the key is absent.

Solution
import json
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
for c in customers[:6]:
print(c["customer_id"], c["address"].get("postal_code", "unknown"))
missing = [c["customer_id"] for c in customers if "postal_code" not in c["address"]]
print("missing:", missing)
assert missing == ["C00005", "C00014"]
Output
C00001 81790
C00002 62260
C00003 45915
C00004 78449
C00005 unknown
C00006 48100
missing: ['C00005', 'C00014']

How it works:

  1. c["address"]["postal_code"] raises KeyError when the key is absent, which stops the loop at C00005.
  2. .get("postal_code", "unknown") returns the default instead.
  3. "postal_code" not in c["address"] tests for the key directly, which is the clearest way to list the gaps.

Alternative: try/except KeyError around the lookup also works. Prefer .get() for one optional key, and try when a missing key is a real error that you want to log.

M07-C07 · Read files of unknown encoding with a fallback

Section titled “M07-C07 · Read files of unknown encoding with a fallback”
Core

A pipeline receives text files from several sources, and nobody recorded their encodings. Write a function read_text_any(path) that tries "utf-8-sig" first and falls back to "latin-1" when decoding fails. It returns the text and the encoding it used. First create an Excel-style file with a BOM, output/stores_excel.csv. Then load the four files below and print, for each one, its name, the encoding used and the start of its first line.

Expected output
stores.csv utf-8-sig 'store_id,city,region,siz'
messy_names.txt utf-8-sig ' josé GARCÍA '
legacy_latin1.csv latin-1 'supplier_id,supplier,cit'
stores_excel.csv utf-8-sig 'store_id,city'
Starter
from pathlib import Path
def read_text_any(path):
# TODO: try path.read_text(encoding="utf-8-sig"); on UnicodeDecodeError use "latin-1"
# TODO: return (text, encoding)
pass
Path("output").mkdir(parents=True, exist_ok=True)
excel = Path("output/stores_excel.csv")
excel.write_text("store_id,city\nS01,Chicago\n", encoding="utf-8-sig")
files = [Path("data/stores.csv"), Path("data/messy_names.txt"),
Path("data/legacy_latin1.csv"), excel]
# TODO: call read_text_any() for each file and print the results
Hint 1

"utf-8-sig" reads plain UTF-8 files too. It only removes a BOM when one is there.

Hint 2

The order matters. Latin-1 maps every byte to a character, so it never fails. It must be the last choice, or it would “succeed” on every file and garble the UTF-8 ones.

Solution
from pathlib import Path
def read_text_any(path):
try:
return path.read_text(encoding="utf-8-sig"), "utf-8-sig"
except UnicodeDecodeError:
return path.read_text(encoding="latin-1"), "latin-1"
Path("output").mkdir(parents=True, exist_ok=True)
excel = Path("output/stores_excel.csv")
excel.write_text("store_id,city\nS01,Chicago\n", encoding="utf-8-sig")
files = [Path("data/stores.csv"), Path("data/messy_names.txt"),
Path("data/legacy_latin1.csv"), excel]
results = {}
for path in files:
text, encoding = read_text_any(path)
results[path.name] = (text, encoding)
print(f"{path.name:20} {encoding:10} {text.splitlines()[0][:24]!r}")
assert results["legacy_latin1.csv"][1] == "latin-1"
assert "Café Müller GmbH" in results["legacy_latin1.csv"][0]
assert results["stores_excel.csv"][0].startswith("store_id")
assert excel.read_bytes().startswith(b"\xef\xbb\xbf")
Output
stores.csv utf-8-sig 'store_id,city,region,siz'
messy_names.txt utf-8-sig ' josé GARCÍA '
legacy_latin1.csv latin-1 'supplier_id,supplier,cit'
stores_excel.csv utf-8-sig 'store_id,city'

How it works:

  1. read_text() with "utf-8-sig" decodes UTF-8 and drops a BOM if the file has one, so stores_excel.csv starts with store_id, not 'store_id'.
  2. The legacy file is not valid UTF-8, so the first attempt raises UnicodeDecodeError, and the except branch reads it as Latin-1.
  3. messy_names.txt holds accented names in UTF-8. It decodes on the first try and keeps its letters intact.
  4. The last assert checks the bytes of the Excel file: the BOM is on disk, but not in the text.

Alternative: a fallback is a guess. Valid UTF-8 almost never happens by accident, so a UTF-8 success is strong evidence, but a Latin-1 result could also be cp1252. Log the encoding you used for each file, and once you know a source’s encoding, write it in the config instead of guessing every run.

M07-C08 · Refactor: open, close and string paths

Section titled “M07-C08 · Refactor: open, close and string paths”
Core

Refactor: this script works, but it opens and closes files by hand and builds paths by gluing strings. Rewrite it with pathlib and with, and keep the same output.

import os
folder = "output"
if not os.path.exists(folder):
os.mkdir(folder)
f = open("data/stores.csv", encoding="utf-8")
lines = f.readlines()
f.close()
out = open(folder + "/" + "store_ids.txt", "w", encoding="utf-8")
for line in lines[1:]:
out.write(line.split(",")[0] + "\n")
out.close()
print(open(folder + "/" + "store_ids.txt", encoding="utf-8").read().split())
Output
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11', 'S12']
Expected output
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11', 'S12']
Starter
import csv
from pathlib import Path
# TODO: create output/ with mkdir(parents=True, exist_ok=True)
# TODO: read the store ids with csv.DictReader inside a with block
# TODO: write one id per line with write_text(), then print the ids read back
Hint 1

out_dir = Path("output") and out_dir / "store_ids.txt" replace the string gluing.

Hint 2

"\n".join(ids) + "\n" builds the whole file text. write_text() writes it in one call and closes the file.

Solution
import csv
from pathlib import Path
out_dir = Path("output")
out_dir.mkdir(parents=True, exist_ok=True)
with open("data/stores.csv", encoding="utf-8", newline="") as f:
ids = [row["store_id"] for row in csv.DictReader(f)]
target = out_dir / "store_ids.txt"
target.write_text("\n".join(ids) + "\n", encoding="utf-8")
print(target.read_text(encoding="utf-8").split())
assert len(ids) == 12
assert target.read_text(encoding="utf-8").startswith("S01\n")
Output
['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11', 'S12']

How it works:

  1. mkdir(parents=True, exist_ok=True) replaces the exists() check and the mkdir() call, and it does not fail when the folder exists.
  2. with closes the input file. The original last line opened the file again and never closed it.
  3. csv.DictReader takes the id by name, so the code no longer depends on the column position or on split(",").
  4. write_text() and read_text() open, write or read, and close in one call.

Alternative: if you need the file object for a loop, write with open(target, "w", encoding="utf-8") as out: and print(store_id, file=out) inside it.

Core

Write one JSON object per customer of data/customers.json to output/customers.jsonl, with the keys customer_id, plan, n_orders and total (the order amounts, rounded to 2 decimals). Read the file back line by line. Print the first two lines, the line count and the customers with a total above 1,000 USD.

Expected output
{"customer_id": "C00001", "plan": "premium", "n_orders": 5, "total": 1325.54}
{"customer_id": "C00002", "plan": "standard", "n_orders": 3, "total": 961.89}
20 lines
['C00001', 'C00003', 'C00015', 'C00017', 'C00019']
Starter
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
# TODO: load the customers, write one json.dumps(record) + "\n" per customer
# TODO: read the file back with json.loads(line) in a loop and print the results
Hint 1

round(sum(o["amount"] for o in c["orders"]), 2) gives the total of one customer.

Hint 2

Open the output with "w" so that a rerun does not add the records a second time.

Solution
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
target = Path("output/customers.jsonl")
with open(target, "w", encoding="utf-8") as f:
for c in customers:
record = {
"customer_id": c["customer_id"],
"plan": c["plan"],
"n_orders": len(c["orders"]),
"total": round(sum(o["amount"] for o in c["orders"]), 2),
}
f.write(json.dumps(record) + "\n")
with open(target, encoding="utf-8") as f:
records = [json.loads(line) for line in f]
for line in target.read_text(encoding="utf-8").splitlines()[:2]:
print(line)
print(len(records), "lines")
print([r["customer_id"] for r in records if r["total"] > 1000])
assert len(records) == 20
assert all(set(r) == {"customer_id", "plan", "n_orders", "total"} for r in records)
Output
{"customer_id": "C00001", "plan": "premium", "n_orders": 5, "total": 1325.54}
{"customer_id": "C00002", "plan": "standard", "n_orders": 3, "total": 961.89}
20 lines
['C00001', 'C00003', 'C00015', 'C00017', 'C00019']

How it works:

  1. Each json.dumps(record) is one line of valid JSON. The + "\n" separates the records.
  2. Reading back, each line is parsed on its own, so a reader never needs the whole file in memory.
  3. The asserts check the line count and that every record has exactly the four keys.

Alternative: pandas reads the same file with pd.read_json("output/customers.jsonl", lines=True) (module 24).

M07-C10 · Warnings and errors per component

Section titled “M07-C10 · Warnings and errors per component”
Core

Read data/logs/app.log line by line. For lines with the level WARNING or ERROR, count them per component (the word in brackets, such as api). Skip lines without a timestamp. Print the components sorted by name.

Expected output
api ERROR 3
api WARNING 13
db ERROR 2
loader ERROR 2
model WARNING 3
validator WARNING 9
Starter
counts = {}
# TODO: open the log; skip lines that do not start with a digit
# TODO: split each line into date, time, level, component and message
# TODO: count (component, level) pairs for WARNING and ERROR
Hint 1

date, time, level, component, message = line.split(maxsplit=4) splits a log line into five parts.

Hint 2

component.strip("[]") removes the brackets. A tuple (component, level) can be a dict key.

Solution
counts = {}
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f:
if not line[:1].isdigit():
continue
date, time, level, component, message = line.split(maxsplit=4)
if level in ("WARNING", "ERROR"):
key = (component.strip("[]"), level)
counts[key] = counts.get(key, 0) + 1
for (component, level), n in sorted(counts.items()):
print(f"{component:10} {level:8} {n}")
assert sum(n for (_, lvl), n in counts.items() if lvl == "ERROR") == 7
assert sum(n for (_, lvl), n in counts.items() if lvl == "WARNING") == 25
Output
api ERROR 3
api WARNING 13
db ERROR 2
loader ERROR 2
model WARNING 3
validator WARNING 9

How it works:

  1. line[:1].isdigit() is False for the traceback lines, so they are skipped. [:1] also works for an empty line, where line[0] would raise IndexError.
  2. split(maxsplit=4) gives exactly five parts; the message keeps its spaces.
  3. The key (component, level) counts warnings and errors separately for each component.
  4. Sorting the items sorts by component, then by level.

Alternative: module 09 parses each line with one regular expression and counts with collections.Counter: Counter((m["component"], m["level"]) for m in matches).

M07-C11 · Choose and justify: a format for each output

Section titled “M07-C11 · Choose and justify: a format for each output”
Core

Choose and justify: a pipeline produces four outputs. Pick CSV, JSON, JSON Lines or pickle for each, then write a small example of each to output/ to prove it works:

  1. A store table for the finance team, who use Excel.
  2. The settings of one run (model, test_size, features), read by a web dashboard.
  3. One event per processed file, appended during the run.
  4. A cache of a Python dict with tuple keys, read back only by the same script tomorrow.

Print each output file name with the format you chose.

Expected output
stores.csv -> CSV
run_settings.json -> JSON
events.jsonl -> JSON Lines
cache.pkl -> pickle
Starter
import csv
import json
import pickle
from pathlib import Path
out = Path("output")
out.mkdir(parents=True, exist_ok=True)
# TODO: write stores.csv, run_settings.json, events.jsonl and cache.pkl
# TODO: read each one back and print "name -> FORMAT"
Hint 1

Ask who reads the file: a person with Excel, another program, a stream of appends, or only your own Python code.

Hint 2

JSON keys must be strings, so a dict with tuple keys cannot go to JSON without conversion. Pickle stores it as it is, and it is safe here because you load only your own file.

Solution
import csv
import json
import pickle
from pathlib import Path
out = Path("output")
out.mkdir(parents=True, exist_ok=True)
stores = [
{"store_id": "S01", "city": "Chicago"},
{"store_id": "S02", "city": "Minneapolis"},
]
with open(out / "stores.csv", "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["store_id", "city"])
writer.writeheader()
writer.writerows(stores)
settings = {"model": "logistic_regression", "test_size": 0.25, "features": ["age"]}
(out / "run_settings.json").write_text(json.dumps(settings, indent=2), encoding="utf-8")
(out / "events.jsonl").unlink(missing_ok=True)
for name in ["2024-01.csv", "2024-02.csv"]:
with open(out / "events.jsonl", "a", encoding="utf-8") as f:
f.write(json.dumps({"file": name, "status": "ok"}) + "\n")
cache = {("S01", "2024-01"): 10561.84, ("S02", "2024-01"): 6597.92} # sales.csv
with open(out / "cache.pkl", "wb") as f:
pickle.dump(cache, f)
for name, fmt in [("stores.csv", "CSV"), ("run_settings.json", "JSON"),
("events.jsonl", "JSON Lines"), ("cache.pkl", "pickle")]:
print(f"{name:18} -> {fmt}")
with open(out / "stores.csv", encoding="utf-8", newline="") as f:
assert list(csv.DictReader(f)) == stores
assert json.loads((out / "run_settings.json").read_text(encoding="utf-8")) == settings
assert len((out / "events.jsonl").read_text(encoding="utf-8").splitlines()) == 2
with open(out / "cache.pkl", "rb") as f:
assert pickle.load(f) == cache
Output
stores.csv -> CSV
run_settings.json -> JSON
events.jsonl -> JSON Lines
cache.pkl -> pickle

How it works:

  1. CSV for the finance table. It is one flat table, and Excel opens CSV directly.
  2. JSON for the settings. They are nested, typed values (a float, a list) read by another program, possibly not written in Python.
  3. JSON Lines for the events. Each event is appended as one line, so the run never rewrites the file and a crash loses at most the last line.
  4. pickle for the private cache. The tuple keys and floats come back exactly. The risk of pickle does not apply, because the script loads only a file it wrote itself.
  5. The asserts read each file back and compare it with the original data.

Alternative: if the cache might be shared or kept for months, convert the tuple keys to strings ("S01|2024-01") and use JSON instead. You lose a little convenience and gain safety and portability.

M07-C12 · Interpret: where do the extra bytes come from?

Section titled “M07-C12 · Interpret: where do the extra bytes come from?”
Core

Interpret a result: the legacy supplier file data/legacy_latin1.csv has 562 bytes. Example 5 of the lesson read it and wrote a UTF-8 copy with csv.DictWriter, and that copy has 604 bytes. The text is the same. Measure where the 42 extra bytes come from, then explain the result.

Expected output
latin-1 bytes: 562
characters: 562
utf-8 bytes: 591
non-ASCII chars: 29
csv copy bytes: 604
CRLF in copy, source: 13 0
Starter
import csv
from pathlib import Path
raw = Path("data/legacy_latin1.csv").read_bytes()
text = raw.decode("latin-1")
# TODO: print len(raw), len(text) and len(text.encode("utf-8"))
# TODO: count the characters with ord(ch) > 127
# TODO: write a UTF-8 copy with csv.DictWriter, then count its bytes and its b"\r\n"
Hint 1

ord(ch) gives the number of a character. ASCII characters have numbers below 128. In UTF-8, the accented letters of this file take 2 bytes each.

Hint 2

Encoding alone does not explain all 42 bytes. Look at the line endings of the CSV copy with read_bytes(): the csv module ends every row with \r\n by default.

Solution
import csv
from pathlib import Path
raw = Path("data/legacy_latin1.csv").read_bytes()
text = raw.decode("latin-1")
non_ascii = [ch for ch in text if ord(ch) > 127]
print("latin-1 bytes: ", len(raw))
print("characters: ", len(text))
print("utf-8 bytes: ", len(text.encode("utf-8")))
print("non-ASCII chars: ", len(non_ascii))
Path("output").mkdir(parents=True, exist_ok=True)
copy = Path("output/suppliers_check.csv")
with open("data/legacy_latin1.csv", encoding="latin-1", newline="") as f:
rows = list(csv.DictReader(f))
with open(copy, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
data = copy.read_bytes()
print("csv copy bytes: ", len(data))
print("CRLF in copy, source:", data.count(b"\r\n"), raw.count(b"\r\n"))
assert len(text.encode("utf-8")) - len(raw) == len(non_ascii)
assert len(data) - len(raw) == len(non_ascii) + data.count(b"\r\n")
Output
latin-1 bytes: 562
characters: 562
utf-8 bytes: 591
non-ASCII chars: 29
csv copy bytes: 604
CRLF in copy, source: 13 0

How it works:

  1. In Latin-1, one character is one byte, so 562 bytes are 562 characters.
  2. In UTF-8, ASCII characters still take one byte, and the 29 accented letters take two. Encoding adds 29 bytes: 591.
  3. The source file ends its lines with \n. The csv module writes \r\n after each of the 13 lines (header plus 12 rows), the line ending of the CSV standard (RFC 4180). That adds 13 bytes: 604.
  4. Interpretation: the size changed for two reasons, and neither is a change of content. A size check between two files is not a content check; compare the decoded rows instead. If a tool needs \n endings, pass lineterminator="\n" to the writer.

Alternative: sum(len(ch.encode("utf-8")) for ch in text) computes the UTF-8 size character by character and also gives 591.

M07-C13 · Cache an expensive result with pickle

Section titled “M07-C13 · Cache an expensive result with pickle”
Core

Revenue per category over the 20,228 rows of data/sales.csv takes only milliseconds, but treat it as a stand-in for a slow step, such as a big database query or a model fit. Write a function revenue_by_category(cache_path) that loads the result from a pickle cache when the file exists, and otherwise computes it from the CSV and saves it. Call the function twice and print where each result came from.

Expected output
computed 1808108.17
cache 1808108.17
6 categories, equal: True
Starter
import csv
import pickle
from pathlib import Path
def revenue_by_category(cache_path):
# TODO: if cache_path exists, load it with pickle ("rb") and return (data, "cache")
# TODO: else read data/sales.csv, sum revenue per category, round to 2 decimals,
# save with pickle ("wb") and return (data, "computed")
pass
Path("output").mkdir(parents=True, exist_ok=True)
cache = Path("output/revenue_cache.pkl")
cache.unlink(missing_ok=True)
# TODO: call the function twice and print the source and the Electronics revenue
Hint 1

cache_path.exists() decides which branch runs. Return a tuple (data, source).

Hint 2

Round once at the end: {k: round(v, 2) for k, v in totals.items()}. Rounding on every addition adds small errors.

Solution
import csv
import pickle
from pathlib import Path
def revenue_by_category(cache_path):
if cache_path.exists():
with open(cache_path, "rb") as f:
return pickle.load(f), "cache"
totals = {}
with open("data/sales.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
category = row["category"]
totals[category] = totals.get(category, 0) + float(row["revenue"])
data = {k: round(v, 2) for k, v in sorted(totals.items())}
with open(cache_path, "wb") as f:
pickle.dump(data, f)
return data, "computed"
Path("output").mkdir(parents=True, exist_ok=True)
cache = Path("output/revenue_cache.pkl")
cache.unlink(missing_ok=True)
first, source_1 = revenue_by_category(cache)
second, source_2 = revenue_by_category(cache)
print(source_1, first["Electronics"])
print(source_2, second["Electronics"])
print(len(first), "categories, equal:", first == second)
assert (source_1, source_2) == ("computed", "cache")
assert first == second
Output
computed 1808108.17
cache 1808108.17
6 categories, equal: True

How it works:

  1. The first call finds no cache file, reads the CSV, computes the totals and saves them with pickle.dump().
  2. The second call finds the file and returns pickle.load() at once, without reading the CSV.
  3. cache.unlink(missing_ok=True) makes the demo start from a clean state on every run.
  4. Loading this pickle is safe, because the script loads only a file it wrote itself.

Alternative: a cache must be invalidated when the input changes. Store the input’s size and modification time (Path("data/sales.csv").stat()) in the cache, and recompute when they differ. Module 09 shows functools.lru_cache for caches that live in memory.

M07-X01 · Combine paginated API responses into one table

Section titled “M07-X01 · Combine paginated API responses into one table”
Challenge

A product API returns 10 products per page. A nightly job saved the three pages as data/api/products_page_1.json … products_page_3.json. Combine them into output/products_api.csv, one row per product. First check the pages: they must be numbered 1 to total_pages with no gaps, the product count must equal total, and only the last page may have next set to null. Flatten the nested price and rating fields into the columns price, currency, rating and reviews. Print the checks and the products that are out of stock.

Sort the pages by their page number, not by file name: as text, products_page_10.json comes before products_page_2.json.

Expected output
text order: ['products_page_1.json', 'products_page_10.json', 'products_page_2.json']
number order: ['products_page_1.json', 'products_page_2.json', 'products_page_10.json']
pages: [1, 2, 3] complete: True
products: 30 expected: 30
next is null only on the last page: True
out of stock: [('P006', 'Espresso Machine'), ('P019', 'Fitness Tracker')]
Starter
import csv
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
# TODO: glob products_page_*.json, load each page, sort the pages by page["page"]
# TODO: check the page numbers, the total and the "next" links
# TODO: flatten each product, write output/products_api.csv, read it back
Hint 1

sorted(names) sorts text character by character. sorted(paths, key=lambda p: int(p.stem.rsplit("_", 1)[1])) sorts by the number after the last underscore. Sorting the loaded pages with key=lambda page: page["page"] uses the number the API itself reports.

Hint 2

[page["page"] for page in pages] == list(range(1, pages[0]["total_pages"] + 1)) checks the numbering. [page["next"] is None for page in pages] must be False for every page except the last.

Hint 3

Flatten with chained keys: item["price"]["amount"], item["rating"]["average"]. Build one new dict per product with exactly the output columns.

Solution
import csv
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
names = ["products_page_10.json", "products_page_2.json", "products_page_1.json"]
print("text order: ", sorted(names))
print("number order:", sorted(names, key=lambda n: int(n[:-5].rsplit("_", 1)[1])))
pages = []
for path in Path("data/api").glob("products_page_*.json"):
with open(path, encoding="utf-8") as f:
pages.append(json.load(f))
pages.sort(key=lambda page: page["page"])
numbers = [page["page"] for page in pages]
total_pages = pages[0]["total_pages"]
products = [item for page in pages for item in page["data"]]
last_flags = [page["next"] is None for page in pages]
print("pages:", numbers, "complete:", numbers == list(range(1, total_pages + 1)))
print("products:", len(products), "expected:", pages[0]["total"])
expected_flags = [False] * (total_pages - 1) + [True]
print("next is null only on the last page:", last_flags == expected_flags)
rows = [
{
"product_id": item["id"],
"name": item["name"],
"category": item["category"],
"price": item["price"]["amount"],
"currency": item["price"]["currency"],
"in_stock": item["in_stock"],
"rating": item["rating"]["average"],
"reviews": item["rating"]["count"],
}
for item in products
]
target = Path("output/products_api.csv")
with open(target, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
with open(target, encoding="utf-8", newline="") as f:
back = list(csv.DictReader(f))
out_of_stock = [(r["product_id"], r["name"]) for r in back if r["in_stock"] == "False"]
print("out of stock:", out_of_stock)
assert numbers == [1, 2, 3]
assert len(back) == pages[0]["total"] == 30
assert len({r["product_id"] for r in back}) == 30
Output
text order: ['products_page_1.json', 'products_page_10.json', 'products_page_2.json']
number order: ['products_page_1.json', 'products_page_2.json', 'products_page_10.json']
pages: [1, 2, 3] complete: True
products: 30 expected: 30
next is null only on the last page: True
out of stock: [('P006', 'Espresso Machine'), ('P019', 'Fitness Tracker')]

How it works:

  1. The first two lines show the trap: text order puts page 10 before page 2. The key function turns the number after the last underscore into an int.
  2. The solution sorts the loaded pages by the page field, the number the API reports, so the file names do not matter at all.
  3. Three checks guard against a broken download: no missing page, the right number of products, and a next link on every page except the last.
  4. The nested comprehension [item for page in pages for item in page["data"]] joins the three data lists in page order.
  5. Flattening picks the nested values with chained keys. The CSV stores True/False as text, so the filter compares with the string "False".

Alternative: module 16 fetches the same pages from a live API and follows the next links until they are null, which needs no page numbers at all. Saving each raw page first, as here, lets you rerun the parsing without calling the API again.

Challenge

Walk the whole data/ tree with Path.walk(). Skip hidden files (names that start with a dot, such as the .DS_Store files that macOS Finder creates). Count the files and add up their sizes per suffix (.csv, .json, and so on). Save the inventory as output/inventory.json, sorted by suffix, with an entry "total". Print a table from the saved file.

Expected output
.csv 17 files 3,945,274 bytes
.db 1 files 2,678,784 bytes
.html 1 files 8,428 bytes
.json 8 files 50,389 bytes
.log 1 files 50,124 bytes
.parquet 1 files 16,243 bytes
.txt 2 files 561 bytes
.xlsx 1 files 36,485 bytes
total 32 files 6,786,288 bytes
Starter
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
inventory = {}
# TODO: for dirpath, dirnames, filenames in Path("data").walk(): ...
# TODO: per suffix, keep {"files": n, "bytes": total}
# TODO: add a "total" entry, save with json.dump(..., indent=2), read back, print
Hint 1

(dirpath / name).suffix gives the suffix and (dirpath / name).stat().st_size the size.

Hint 2

inventory.setdefault(suffix, {"files": 0, "bytes": 0}) returns the entry for a suffix and creates it on first use.

Solution
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
inventory = {}
for dirpath, dirnames, filenames in Path("data").walk():
dirnames.sort()
for name in sorted(filenames):
if name.startswith("."): # hidden files such as .DS_Store
continue
path = dirpath / name
entry = inventory.setdefault(path.suffix, {"files": 0, "bytes": 0})
entry["files"] += 1
entry["bytes"] += path.stat().st_size
report = dict(sorted(inventory.items()))
report["total"] = {
"files": sum(e["files"] for e in inventory.values()),
"bytes": sum(e["bytes"] for e in inventory.values()),
}
target = Path("output/inventory.json")
target.write_text(json.dumps(report, indent=2), encoding="utf-8")
saved = json.loads(target.read_text(encoding="utf-8"))
for suffix, entry in saved.items():
print(f"{suffix:9} {entry['files']:3} files {entry['bytes']:>11,} bytes")
assert saved == report
assert saved["total"]["files"] == 32
Output
.csv 17 files 3,945,274 bytes
.db 1 files 2,678,784 bytes
.html 1 files 8,428 bytes
.json 8 files 50,389 bytes
.log 1 files 50,124 bytes
.parquet 1 files 16,243 bytes
.txt 2 files 561 bytes
.xlsx 1 files 36,485 bytes
total 32 files 6,786,288 bytes

How it works:

  1. Path.walk() yields one folder at a time with the names of its subfolders and files. Sorting both makes the walk order fixed, and the startswith(".") test skips hidden files, so the counts are the same on every machine.
  2. setdefault() creates the entry for a new suffix and returns the existing one afterwards, so one line handles both cases.
  3. dict(sorted(...)) sorts the suffixes before the total entry is added at the end.
  4. The table is printed from the saved file, which proves that the JSON round trip works.

Alternative: Path("data").rglob("*") with if path.is_file() gives the same files in one loop. Use walk() when you also need per-folder results, such as the size of each subfolder.

M07-X03 · Turn the log into a table of pipeline runs

Section titled “M07-X03 · Turn the log into a table of pipeline runs”
Challenge

Each pipeline run in data/logs/app.log starts with Starting pipeline run-NNNN, logs a model score roc_auc=0.8xx and ends with Finished run-NNNN status=.... Build one row per run with run_id, start (the clock time), roc_auc and status, and save the rows to output/pipeline_runs.csv. The team’s threshold is 0.820. Print the runs below it and the mean score.

Expected output
run-0001 08:25:13 0.813 success
run-0002 10:17:07 0.814 success
run-0008 15:35:25 0.812 success
3 of 9 runs below 0.820, mean 0.8260
Starter
import csv
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
runs = []
# TODO: loop over the log; on "Starting pipeline" start a new dict in runs
# TODO: on "roc_auc=" and on "Finished" fill the last dict
# TODO: write output/pipeline_runs.csv, then print the runs below 0.820 and the mean
Hint 1

The run id is the second-to-last word of the start line: line.split()[-2]. The clock time is line[11:19].

Hint 2

runs[-1] is the run in progress. line.rsplit("roc_auc=", 1)[1] is the score text; line.rsplit("status=", 1)[1].strip() is the status.

Hint 3

Only the model line contains roc_auc= with an equals sign. The warning line roc_auc 0.813 below threshold has a space instead.

Solution
import csv
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
runs = []
with open("data/logs/app.log", encoding="utf-8") as f:
for line in f:
if "Starting pipeline" in line:
runs.append({"run_id": line.split()[-2], "start": line[11:19]})
elif "roc_auc=" in line:
runs[-1]["roc_auc"] = float(line.rsplit("roc_auc=", 1)[1])
elif "] Finished run-" in line:
runs[-1]["status"] = line.rsplit("status=", 1)[1].strip()
target = Path("output/pipeline_runs.csv")
with open(target, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["run_id", "start", "roc_auc", "status"])
writer.writeheader()
writer.writerows(runs)
with open(target, encoding="utf-8", newline="") as f:
table = list(csv.DictReader(f))
threshold = 0.820
below = [r for r in table if float(r["roc_auc"]) < threshold]
for r in below:
print(r["run_id"], r["start"], r["roc_auc"], r["status"])
mean = sum(float(r["roc_auc"]) for r in table) / len(table)
print(f"{len(below)} of {len(table)} runs below {threshold:.3f}, mean {mean:.4f}")
assert len(table) == 9
assert all(r["status"] == "success" for r in table)
Output
run-0001 08:25:13 0.813 success
run-0002 10:17:07 0.814 success
run-0008 15:35:25 0.812 success
3 of 9 runs below 0.820, mean 0.8260

How it works:

  1. A start line opens a new dict at the end of runs. Later lines of the same run fill runs[-1], the run in progress.
  2. rsplit(marker, 1)[1] takes the text after the last marker. strip() removes the \n.
  3. DictWriter writes the four keys in a fixed order. The CSV is the table that a dashboard or pandas can read.
  4. Reading the CSV back gives strings, so the comparisons convert roc_auc with float().

Alternative: the log also has a WARNING [model] roc_auc ... below threshold line for each weak run. Counting those lines is shorter, but it trusts the logger’s threshold. Computing from the scores lets you change the threshold yourself.

Challenge

data/config.json has "output": {"dir": "output/", "overwrite": false}. Write a function export_rows(rows, path, overwrite) that writes a CSV with mode "w" when overwrite is true and with mode "x" otherwise. When the file exists and overwriting is off, it must not touch the file: catch FileExistsError, print a message and return False. Demonstrate it with the config settings: export twice, then once with overwrite=True.

Expected output
wrote 3 rows to output/store_export.csv
skip: output/store_export.csv exists (overwrite is off)
wrote 12 rows to output/store_export.csv
[True, False, True] 4 13
Starter
import csv
import json
from pathlib import Path
def export_rows(rows, path, overwrite):
# TODO: choose the mode, open with newline="", write with DictWriter
# TODO: on FileExistsError print "skip: <path> exists (overwrite is off)" and return False
pass
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
out_dir = Path(config["output"]["dir"])
out_dir.mkdir(parents=True, exist_ok=True)
target = out_dir / "store_export.csv"
target.unlink(missing_ok=True)
# TODO: export twice with the config setting, then once with overwrite=True
Hint 1

mode = "w" if overwrite else "x". Put the open() call inside try.

Hint 2

Mode "x" raises FileExistsError at the open() call, before anything is written, so the old file stays as it was.

Solution
import csv
import json
from pathlib import Path
def export_rows(rows, path, overwrite):
mode = "w" if overwrite else "x"
try:
with open(path, mode, encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
except FileExistsError:
print(f"skip: {path.as_posix()} exists (overwrite is off)")
return False
print(f"wrote {len(rows)} rows to {path.as_posix()}")
return True
config = json.loads(Path("data/config.json").read_text(encoding="utf-8"))
out_dir = Path(config["output"]["dir"])
out_dir.mkdir(parents=True, exist_ok=True)
target = out_dir / "store_export.csv"
target.unlink(missing_ok=True)
with open("data/stores.csv", encoding="utf-8", newline="") as f:
stores = list(csv.DictReader(f))
first = export_rows(stores[:3], target, config["output"]["overwrite"])
second = export_rows(stores, target, config["output"]["overwrite"])
lines_after_skip = len(target.read_text(encoding="utf-8").splitlines())
third = export_rows(stores, target, overwrite=True)
lines_after_overwrite = len(target.read_text(encoding="utf-8").splitlines())
print([first, second, third], lines_after_skip, lines_after_overwrite)
assert (first, second, third) == (True, False, True)
assert lines_after_skip == 4
Output
wrote 3 rows to output/store_export.csv
skip: output/store_export.csv exists (overwrite is off)
wrote 12 rows to output/store_export.csv
[True, False, True] 4 13

How it works:

  1. The config gives the output folder and the overwrite flag, so the policy lives in one place.
  2. With overwrite false, the mode is "x". The first export creates the file with 3 stores.
  3. The second export raises FileExistsError in open(). The except branch prints the message and returns False. The file still has its 4 lines (header plus 3 rows).
  4. With overwrite=True, mode "w" replaces the file with all 12 stores.

Alternative: if path.exists() and not overwrite: checks before opening. It reads well, but another process could create the file between the check and the open(). Mode "x" checks and creates in one step, which is safer when several jobs write to the same folder.

M07-X05 · Fix the bugs: a monthly merge script

Section titled “M07-X05 · Fix the bugs: a monthly merge script”
Challenge

Fix the bugs: a colleague wrote this script to merge the monthly reports. It has five problems: it writes into data/, processes files in an unsorted order, has no encodings, glues lines together (so headers repeat and April’s columns are misplaced), and computes revenue by position. Do not run it: it writes into the data folder.

merge_reports.py (buggy)
from pathlib import Path
out = open("data/reports/all.csv", "w")
total = 0.0
for path in Path("data/reports").glob("*.csv"):
for line in open(path):
out.write(line)
if not line.startswith("order"):
total += float(line.strip().split(",")[6])
out.close()
print("total revenue:", round(total, 2))

Write a fixed version that writes output/all_reports.csv, and print the row count, the number of header lines in the output and the total revenue.

Expected output
rows: 297 header lines: 1
total revenue: 57,266.39 USD
Starter
import csv
from pathlib import Path
# TODO: create output/, sort the input files, open every file with encoding="utf-8"
# TODO: copy rows by name with DictReader/DictWriter (newline="")
# TODO: total the revenue by name; count the rows and the header lines of the output
Hint 1

The total reads column 6, which is quantity in April’s rows. Reading by name fixes it.

Hint 2

Count the header lines of the output with sum(1 for line in lines if line.startswith("order_id,")). A correct merge has exactly one.

Solution
import csv
from pathlib import Path
out_dir = Path("output")
out_dir.mkdir(parents=True, exist_ok=True)
files = sorted(Path("data/reports").glob("2024-*.csv"))
columns = ["order_id", "order_date", "store_id", "product", "category", "quantity",
"revenue"]
target = out_dir / "all_reports.csv"
total = 0.0
rows = 0
with open(target, "w", encoding="utf-8", newline="") as out:
writer = csv.DictWriter(out, fieldnames=columns)
writer.writeheader()
for path in files:
with open(path, encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
writer.writerow(row)
total += float(row["revenue"])
rows += 1
lines = target.read_text(encoding="utf-8").splitlines()
headers = sum(1 for line in lines if line.startswith("order_id,"))
print("rows:", rows, " header lines:", headers)
print(f"total revenue: {total:,.2f} USD")
assert rows == len(lines) - 1 == 297
assert headers == 1
assert round(total, 2) == 57266.39
Output
rows: 297 header lines: 1
total revenue: 57,266.39 USD

How it works:

  1. Output folder. The result goes to output/. In data/reports/, the next run’s glob("*.csv") would read all.csv as a seventh report and double every number.
  2. Sorted input. sorted() fixes the order of the rows in the output on every machine. The pattern 2024-*.csv also skips any other CSV in the folder.
  3. Encodings and closing. Every open() has encoding="utf-8" and sits in a with block. The buggy inner open(path) was never closed.
  4. One header, rows by name. DictWriter writes one header; DictReader maps April’s columns by name, so revenue is always the revenue.
  5. The buggy script also wrote April’s rows in April’s column order under January’s header, so every tool that reads all.csv later would misread them.

Alternative: if you must keep every file’s own columns, write one output file per input (out_dir / path.name) after cleaning, and combine later with pandas concat, which aligns by name.

M07-X06 · Flatten customers, keeping those without orders

Section titled “M07-X06 · Flatten customers, keeping those without orders”
Challenge

Flatten data/customers.json to output/customers_flat.csv with one row per order. Keep customers without orders as one row with empty order fields, so no customer disappears. Columns: customer_id, name, plan, city, tags (joined with |), phone (empty if absent or null), order_id, date, amount. Print the row counts and the rows for customer C00008.

Expected output
51 rows: 48 orders + 3 customers without orders
20 distinct customers
['C00008', 'Diego Ramos', 'standard', 'Chicago', '', '', '', '', '']
Starter
import csv
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
columns = ["customer_id", "name", "plan", "city", "tags", "phone", "order_id", "date",
"amount"]
rows = []
# TODO: build the customer part of the row once per customer
# TODO: one row per order, or one row with empty order fields if there are no orders
# TODO: write the CSV, read it back and print the checks
Hint 1

"|".join(c["tags"]) gives "" for an empty tag list. c.get("phone") or "" turns both a missing key and null into "".

Hint 2

for order in c["orders"] or [{}]: loops over a list with one empty dict when there are no orders. order.get("order_id", "") then gives the empty fields. The dict merge operator a | b (Python 3.9+) builds a new dict with the keys of both; for a shared key, b wins.

Solution
import csv
import json
from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)
columns = ["customer_id", "name", "plan", "city", "tags", "phone", "order_id", "date",
"amount"]
with open("data/customers.json", encoding="utf-8") as f:
customers = json.load(f)["customers"]
rows = []
for c in customers:
base = {
"customer_id": c["customer_id"],
"name": c["name"],
"plan": c["plan"],
"city": c["address"]["city"],
"tags": "|".join(c["tags"]),
"phone": c.get("phone") or "",
}
for order in c["orders"] or [{}]:
rows.append(
base
| {
"order_id": order.get("order_id", ""),
"date": order.get("date", ""),
"amount": order.get("amount", ""),
}
)
target = Path("output/customers_flat.csv")
with open(target, "w", encoding="utf-8", newline="") as f:
writer = csv.DictWriter(f, fieldnames=columns)
writer.writeheader()
writer.writerows(rows)
with open(target, encoding="utf-8", newline="") as f:
back = list(csv.DictReader(f))
with_orders = [r for r in back if r["order_id"]]
print(len(back), "rows:", len(with_orders), "orders +", len(back) - len(with_orders),
"customers without orders")
print(len({r["customer_id"] for r in back}), "distinct customers")
for r in back:
if r["customer_id"] == "C00008":
print(list(r.values()))
assert len(with_orders) == 48
assert len({r["customer_id"] for r in back}) == 20
Output
51 rows: 48 orders + 3 customers without orders
20 distinct customers
['C00008', 'Diego Ramos', 'standard', 'Chicago', '', '', '', '', '']

How it works:

  1. base holds the customer fields, computed once per customer.
  2. c["orders"] or [{}] replaces an empty list with a list that holds one empty dict, so the inner loop runs once and the customer keeps one row.
  3. base | {...} (the dict merge operator) builds a new dict per row, so the rows do not share one dict.
  4. Reading back, the empty order id marks the customers without orders. The assert checks that all 20 customers survive the flattening.

Alternative: pandas has pd.json_normalize(customers, record_path="orders", meta=["customer_id", "plan"]), which flattens in one call. It drops customers with an empty orders list, so you would add them back with a merge, the same decision you made here by hand.