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:
- Read the task and the expected output.
- Copy the starter code into a script (for example
exercise.py) in your project folder, next todata/. Replace each to-do comment with your code. - Run the script with
python exercise.pyfrom the project folder. Compare your output with the expected output. - 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
Section titled “Warm-up”M07-W01 · Take a path apart
Section titled “M07-W01 · Take a path apart”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.
name: 2024-04.csvstem: 2024-04suffix: .csvparent: data/reportsdata/reports/2024-04_clean.csvdata/reports/2024-04.jsonfrom 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 suffixHint 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.nameassert clean.parent == report.parentassert as_json.stem == report.stemname: 2024-04.csvstem: 2024-04suffix: .csvparent: data/reportsdata/reports/2024-04_clean.csvdata/reports/2024-04.jsonHow it works:
- The
/operator joins the three parts into onePath. nameis the last part.stemdrops the suffix, andsuffixkeeps the dot.with_name()replaces the whole last part;with_suffix()replaces only the extension. Both return new paths and leavereportunchanged.- 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.
M07-W02 · Count the lines of a file
Section titled “M07-W02 · Count the lines of a file”Open data/readings.txt with with open(...) and loop over the file. Count all lines and the lines that are empty after strip().
lines: 43empty: 1total = 0empty = 0# TODO: open data/readings.txt with encoding="utf-8" and loop over the lines# TODO: print the two countsHint 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 = 0empty = 0with open("data/readings.txt", encoding="utf-8") as f: for line in f: total += 1 if not line.strip(): empty += 1print("lines:", total)print("empty:", empty)assert total == 43assert empty == 1lines: 43empty: 1How it works:
withopens the file and closes it after the loop.- Each pass of the loop reads one line, so the file is never in memory as a whole.
- 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.
M07-W03 · Predict the output: file modes
Section titled “M07-W03 · Predict the output: file modes”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.
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 codeHint 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"]'run 3\nrun 4\n'How it works:
- The first
"w"creates the file withrun 1. The"a"addsrun 2. - The second
"w"erases both lines before it writesrun 3. - The last
"a"addsrun 4afterrun 3. repr()shows the\ncharacters, 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”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 = 40with open("output/count.txt", "w", encoding="utf-8") as f: f.write(valid_count)TypeError: write() argument must be str, not intFix the write() line so that the file holds valid_readings=40 and a line break, then print the file content with repr():
'valid_readings=40\n'from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)valid_count = 40with 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 = 40with 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"'valid_readings=40\n'How it works:
- A file opened in text mode needs a
str.write(40)raisesTypeError, because Python does not convert numbers for you. - The f-string turns the number into text and adds the label.
- 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.
M07-W05 · Read a CSV header
Section titled “M07-W05 · Read a CSV header”Use csv.reader to read data/stores.csv. Print the header row, then count the data rows.
['store_id', 'city', 'region', 'size_sqm', 'opened']12 storesimport 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 countHint 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['store_id', 'city', 'region', 'size_sqm', 'opened']12 storesHow it works:
csv.readergives each row as a list of strings.next(reader)consumes the header, solist(reader)holds only the 12 store rows.- Both calls are inside the
withblock. 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.
M07-W06 · Load a JSON config
Section titled “M07-W06 · Load a JSON config”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.
sales-pipeline 1.4.0data/reports/[1, 2, 4]<class 'dict'>import json
# TODO: open data/config.json and load it into config# TODO: print the four linesHint 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]sales-pipeline 1.4.0data/reports/[1, 2, 4]<class 'dict'>How it works:
json.load()turns the JSON object into a dict, the array into a list and the numbers intointvalues.- Two keys in a row walk one level down the nesting.
thresholdsis 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”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.
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 codeHint 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 Trueassert back["limits"] == [19.0, 23.0]assert back != record{"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:
json.dumps()writesTrueastrue,Noneasnulland the tuple as an array[19.0, 23.0].- The int key
1becomes the string"1", because JSON keys must be strings. 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.
M07-W08 · Text to bytes and back
Section titled “M07-W08 · Text to bytes and back”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.
b'Z\xc3\xbcrich' 7b'Z\xfcrich' 6Zürich Zürich 6city = "Zürich"# TODO: encode with "utf-8" and "latin-1"# TODO: print each bytes value with its length, then the decoded textHint 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) + 1assert as_latin1.decode("latin-1") == cityb'Z\xc3\xbcrich' 7b'Z\xfcrich' 6Zürich Zürich 6How it works:
ü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.- So the same 6 characters take 7 bytes in UTF-8 and 6 in Latin-1.
- 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.
M07-W09 · List the files in a folder
Section titled “M07-W09 · List the files in a folder”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.
error_429.jsonproducts_page_1.jsonproducts_page_2.jsonproducts_page_3.jsonusers.jsonweather_forecast.json6 JSON filesfrom pathlib import Path
api_dir = Path("data/api")# TODO: find the .json files with glob(), sort them, print each name and the countHint 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) == 6error_429.jsonproducts_page_1.jsonproducts_page_2.jsonproducts_page_3.jsonusers.jsonweather_forecast.json6 JSON filesHow it works:
glob("*.json")matches names that end in.json. It skipscatalog.html.sorted()gives the same order on every machine.path.nameprints 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”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.
valid: 40 invalid: 3['69.8', '71.4', '70.5']from pathlib import Path
Path("output").mkdir(parents=True, exist_ok=True)valid = 0invalid = 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 fileHint 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 = 0invalid = 0with ( 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 += 1lines = target.read_text(encoding="utf-8").splitlines()print("valid:", valid, "invalid:", invalid)print(lines[:3])assert valid == 40 and invalid == 3assert len(lines) == validvalid: 40 invalid: 3['69.8', '71.4', '70.5']How it works:
- The parenthesized
with(Python 3.10+) opens both files and closes both at the end. float(line)ignores the\nand the surrounding spaces.error, the empty line andn/araiseValueError, socontinueskips them.f"{...:.1f}\n"writes one rounded value per line.- 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.
M07-C02 · Floor area per region
Section titled “M07-C02 · Floor area per region”Read data/stores.csv with csv.DictReader. For each region, count the stores and add up size_sqm. Print the regions in alphabetical order.
East 3 stores 7,210 m²North 3 stores 6,220 m²South 3 stores 7,080 m²West 3 stores 5,720 m²import csv
stores = {}area = {}# TODO: read the file with DictReader and fill both dicts by region# TODO: print one line per region, sortedHint 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()) == 12assert area["North"] == 2850 + 1950 + 1420East 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:
DictReadergives each row as a dict, so the code names the columns it uses.- Two dicts collect the count and the sum per region.
int()converts the area. Without it,+would raiseTypeErrorbecause the value is text.:>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”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) + 1print(sorted(counts.items(), key=lambda item: -item[1])[:4])[('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:
'' 4'-' 4'N/A' 9'online' 507'store' 676import csv
counts = {}# TODO: read data/sales_raw.csv with csv.DictReader# TODO: count row["channel"] and print the counts sorted by channelHint 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) + 1for channel in sorted(counts): print(repr(channel), counts[channel])assert sum(counts.values()) == 1200assert set(counts) <= {"store", "online", "", "N/A", "-"}'' 4'-' 4'N/A' 9'online' 507'store' 676How it works:
- 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. csv.DictReaderkeeps a quoted field in one piece and maps every value to its column name.- 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. - 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”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.
product_id,product,margin_rateP026,Vitamin C Face Serum,0.748P030,Mineral Sunscreen SPF 50,0.744P014,Running Socks 3-Pack,0.72P027,Hydrating Face Cream,0.716import csvfrom 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 fileHint 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 csvfrom 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)product_id,product,margin_rateP026,Vitamin C Face Serum,0.748P030,Mineral Sunscreen SPF 50,0.744P014,Running Socks 3-Pack,0.72P027,Hydrating Face Cream,0.716How it works:
- The loop converts the two prices and computes the rate for each product.
- Only rows with a rate of at least 0.70 go into
selected, as new dicts with the three output columns. DictWriterwrites the header and the rows in the order offieldnames.- 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”Load data/customers.json. Count the customers per plan, the total number of orders, the customers with no orders and the total order amount.
{'basic': 7, 'premium': 6, 'standard': 7}orders: 48no orders: ['C00008', 'C00012', 'C00013']total amount: 13,711.70 USDimport 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 resultsHint 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 = 0amount = 0.0without = []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()) == 20assert n_orders == 48{'basic': 7, 'premium': 6, 'standard': 7}orders: 48no orders: ['C00008', 'C00012', 'C00013']total amount: 13,711.70 USDHow it works:
json.load(f)["customers"]loads the file and keeps only the list of records.- One loop over the customers fills the plan counts, the order count and the list of customers without orders.
- An inner loop adds the amount of each order.
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”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"])C00001 81790C00002 62260C00003 45915C00004 78449KeyError: 'postal_code'Make it print unknown for a missing postal code, and print every customer whose postal code is missing:
C00001 81790C00002 62260C00003 45915C00004 78449C00005 unknownC00006 48100missing: ['C00005', 'C00014']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 codeHint 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"]C00001 81790C00002 62260C00003 45915C00004 78449C00005 unknownC00006 48100missing: ['C00005', 'C00014']How it works:
c["address"]["postal_code"]raisesKeyErrorwhen the key is absent, which stops the loop at C00005..get("postal_code", "unknown")returns the default instead."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”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.
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'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 resultsHint 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")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:
read_text()with"utf-8-sig"decodes UTF-8 and drops a BOM if the file has one, sostores_excel.csvstarts withstore_id, not'store_id'.- The legacy file is not valid UTF-8, so the first attempt raises
UnicodeDecodeError, and theexceptbranch reads it as Latin-1. messy_names.txtholds accented names in UTF-8. It decodes on the first try and keeps its letters intact.- 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”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())['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11', 'S12']['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11', 'S12']import csvfrom 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 backHint 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 csvfrom 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) == 12assert target.read_text(encoding="utf-8").startswith("S01\n")['S01', 'S02', 'S03', 'S04', 'S05', 'S06', 'S07', 'S08', 'S09', 'S10', 'S11', 'S12']How it works:
mkdir(parents=True, exist_ok=True)replaces theexists()check and themkdir()call, and it does not fail when the folder exists.withcloses the input file. The original last line opened the file again and never closed it.csv.DictReadertakes the id by name, so the code no longer depends on the column position or onsplit(",").write_text()andread_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.
M07-C09 · Write and read JSON Lines
Section titled “M07-C09 · Write and read JSON Lines”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.
{"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']import jsonfrom 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 resultsHint 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 jsonfrom 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) == 20assert all(set(r) == {"customer_id", "plan", "n_orders", "total"} for r in records){"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:
- Each
json.dumps(record)is one line of valid JSON. The+ "\n"separates the records. - Reading back, each line is parsed on its own, so a reader never needs the whole file in memory.
- 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”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.
api ERROR 3api WARNING 13db ERROR 2loader ERROR 2model WARNING 3validator WARNING 9counts = {}# 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 ERRORHint 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) + 1for (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") == 7assert sum(n for (_, lvl), n in counts.items() if lvl == "WARNING") == 25api ERROR 3api WARNING 13db ERROR 2loader ERROR 2model WARNING 3validator WARNING 9How it works:
line[:1].isdigit()isFalsefor the traceback lines, so they are skipped.[:1]also works for an empty line, whereline[0]would raiseIndexError.split(maxsplit=4)gives exactly five parts; the message keeps its spaces.- The key
(component, level)counts warnings and errors separately for each component. - 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”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:
- A store table for the finance team, who use Excel.
- The settings of one run (
model,test_size,features), read by a web dashboard. - One event per processed file, appended during the run.
- 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.
stores.csv -> CSVrun_settings.json -> JSONevents.jsonl -> JSON Linescache.pkl -> pickleimport csvimport jsonimport picklefrom 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 csvimport jsonimport picklefrom 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.csvwith 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)) == storesassert json.loads((out / "run_settings.json").read_text(encoding="utf-8")) == settingsassert len((out / "events.jsonl").read_text(encoding="utf-8").splitlines()) == 2with open(out / "cache.pkl", "rb") as f: assert pickle.load(f) == cachestores.csv -> CSVrun_settings.json -> JSONevents.jsonl -> JSON Linescache.pkl -> pickleHow it works:
- CSV for the finance table. It is one flat table, and Excel opens CSV directly.
- JSON for the settings. They are nested, typed values (a float, a list) read by another program, possibly not written in Python.
- 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.
- 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.
- 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?”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.
latin-1 bytes: 562characters: 562utf-8 bytes: 591non-ASCII chars: 29csv copy bytes: 604CRLF in copy, source: 13 0import csvfrom 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 csvfrom 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")latin-1 bytes: 562characters: 562utf-8 bytes: 591non-ASCII chars: 29csv copy bytes: 604CRLF in copy, source: 13 0How it works:
- In Latin-1, one character is one byte, so 562 bytes are 562 characters.
- In UTF-8, ASCII characters still take one byte, and the 29 accented letters take two. Encoding adds 29 bytes: 591.
- The source file ends its lines with
\n. Thecsvmodule writes\r\nafter each of the 13 lines (header plus 12 rows), the line ending of the CSV standard (RFC 4180). That adds 13 bytes: 604. - 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
\nendings, passlineterminator="\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”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.
computed 1808108.17cache 1808108.176 categories, equal: Trueimport csvimport picklefrom 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 revenueHint 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 csvimport picklefrom 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 == secondcomputed 1808108.17cache 1808108.176 categories, equal: TrueHow it works:
- The first call finds no cache file, reads the CSV, computes the totals and saves them with
pickle.dump(). - The second call finds the file and returns
pickle.load()at once, without reading the CSV. cache.unlink(missing_ok=True)makes the demo start from a clean state on every run.- 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.
Challenge
Section titled “Challenge”M07-X01 · Combine paginated API responses into one table
Section titled “M07-X01 · Combine paginated API responses into one table”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.
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: Trueproducts: 30 expected: 30next is null only on the last page: Trueout of stock: [('P006', 'Espresso Machine'), ('P019', 'Fitness Tracker')]import csvimport jsonfrom 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 backHint 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 csvimport jsonfrom 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"] == 30assert len({r["product_id"] for r in back}) == 30text 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: Trueproducts: 30 expected: 30next is null only on the last page: Trueout of stock: [('P006', 'Espresso Machine'), ('P019', 'Fitness Tracker')]How it works:
- 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. - The solution sorts the loaded pages by the
pagefield, the number the API reports, so the file names do not matter at all. - Three checks guard against a broken download: no missing page, the right number of products, and a
nextlink on every page except the last. - The nested comprehension
[item for page in pages for item in page["data"]]joins the threedatalists in page order. - Flattening picks the nested values with chained keys. The CSV stores
True/Falseas 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.
M07-X02 · Inventory a directory tree
Section titled “M07-X02 · Inventory a directory tree”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.
.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 bytestotal 32 files 6,786,288 bytesimport jsonfrom 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, printHint 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 jsonfrom 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 == reportassert saved["total"]["files"] == 32.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 bytestotal 32 files 6,786,288 bytesHow it works:
Path.walk()yields one folder at a time with the names of its subfolders and files. Sorting both makes the walk order fixed, and thestartswith(".")test skips hidden files, so the counts are the same on every machine.setdefault()creates the entry for a new suffix and returns the existing one afterwards, so one line handles both cases.dict(sorted(...))sorts the suffixes before thetotalentry is added at the end.- 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”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.
run-0001 08:25:13 0.813 successrun-0002 10:17:07 0.814 successrun-0008 15:35:25 0.812 success3 of 9 runs below 0.820, mean 0.8260import csvfrom 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 meanHint 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 csvfrom 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.820below = [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) == 9assert all(r["status"] == "success" for r in table)run-0001 08:25:13 0.813 successrun-0002 10:17:07 0.814 successrun-0008 15:35:25 0.812 success3 of 9 runs below 0.820, mean 0.8260How it works:
- A start line opens a new dict at the end of
runs. Later lines of the same run fillruns[-1], the run in progress. rsplit(marker, 1)[1]takes the text after the last marker.strip()removes the\n.DictWriterwrites the four keys in a fixed order. The CSV is the table that a dashboard or pandas can read.- Reading the CSV back gives strings, so the comparisons convert
roc_aucwithfloat().
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.
M07-X04 · Respect the overwrite setting
Section titled “M07-X04 · Respect the overwrite setting”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.
wrote 3 rows to output/store_export.csvskip: output/store_export.csv exists (overwrite is off)wrote 12 rows to output/store_export.csv[True, False, True] 4 13import csvimport jsonfrom 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=TrueHint 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 csvimport jsonfrom 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 == 4wrote 3 rows to output/store_export.csvskip: output/store_export.csv exists (overwrite is off)wrote 12 rows to output/store_export.csv[True, False, True] 4 13How it works:
- The config gives the output folder and the overwrite flag, so the policy lives in one place.
- With
overwritefalse, the mode is"x". The first export creates the file with 3 stores. - The second export raises
FileExistsErrorinopen(). Theexceptbranch prints the message and returnsFalse. The file still has its 4 lines (header plus 3 rows). - 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”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.
from pathlib import Path
out = open("data/reports/all.csv", "w")total = 0.0for 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.
rows: 297 header lines: 1total revenue: 57,266.39 USDimport csvfrom 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 outputHint 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 csvfrom 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.0rows = 0with 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 += 1lines = 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 == 297assert headers == 1assert round(total, 2) == 57266.39rows: 297 header lines: 1total revenue: 57,266.39 USDHow it works:
- Output folder. The result goes to
output/. Indata/reports/, the next run’sglob("*.csv")would readall.csvas a seventh report and double every number. - Sorted input.
sorted()fixes the order of the rows in the output on every machine. The pattern2024-*.csvalso skips any other CSV in the folder. - Encodings and closing. Every
open()hasencoding="utf-8"and sits in awithblock. The buggy inneropen(path)was never closed. - One header, rows by name.
DictWriterwrites one header;DictReadermaps April’s columns by name, sorevenueis always the revenue. - The buggy script also wrote April’s rows in April’s column order under January’s header, so every tool that reads
all.csvlater 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”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.
51 rows: 48 orders + 3 customers without orders20 distinct customers['C00008', 'Diego Ramos', 'standard', 'Chicago', '', '', '', '', '']import csvimport jsonfrom 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 checksHint 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 csvimport jsonfrom 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) == 48assert len({r["customer_id"] for r in back}) == 2051 rows: 48 orders + 3 customers without orders20 distinct customers['C00008', 'Diego Ramos', 'standard', 'Chicago', '', '', '', '', '']How it works:
baseholds the customer fields, computed once per customer.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.base | {...}(the dict merge operator) builds a new dict per row, so the rows do not share one dict.- 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.