Objectives: LO-11.1, LO-11.2, LO-11.3, LO-11.4
Prerequisites: the Module 11 reading and
Lab 9
Time: about 2 hours
In this lab you work with a weather station’s files: you build paths, write and read a text log,
see what a wrong encoding does, read readings from a CSV file and write a summary of them, save
and load a station’s details as JSON, and write recursive functions that search nested data and
a folder tree. As before, each exercise ends with a check cell that prints passed or says what
is wrong, and fails until you answer.
Setup¶
Run the next cell first. It prints the version of Python, deletes anything an earlier run left
in scratch/lab11, and writes the files this lab reads into that folder. LAB is the folder’s
path, as a Path.
import csv
import json
import shutil
import sys
from pathlib import Path
print("Python", sys.version.split()[0])
LAB = Path("scratch") / "lab11"
if LAB.exists():
shutil.rmtree(LAB)
LAB.mkdir(parents=True)
READINGS_CSV = """station,date,temp_c,rain_mm
"Harbor, north pier",2026-11-02,8.5,0.0
"Harbor, north pier",2026-11-03,11.0,2.4
"Harbor, north pier",2026-11-04,6.5,12.0
Hilltop,2026-11-02,4.0,0.6
Hilltop,2026-11-03,7.5,5.5
"""
(LAB / "readings.csv").write_text(READINGS_CSV, encoding="utf-8")
NETWORK = {
"network": "Coast",
"stations": [
{"name": "Harbor", "readings": [{"day": 2, "rain_mm": 0.0}, {"day": 3, "rain_mm": 2.4}]},
{"name": "Hilltop", "readings": [{"day": 2, "rain_mm": 0.6}],
"backup": {"name": "Hilltop B", "readings": [{"day": 2, "rain_mm": 0.8}]}},
],
"contact": {"team": "Field", "rain_mm": None},
}
for name in ["archive/2025/jan.csv", "archive/2025/feb.csv", "archive/2025/notes.txt",
"archive/2024/dec.csv", "archive/readme.txt", "current/nov.csv", "current/nov.json"]:
path = LAB / "tree" / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(f"{name}\n", encoding="utf-8")
print("Ready.")1. Paths¶
Run the next cell. It builds a path from four parts, and prints it.
p = LAB / "stations" / "harbor" / "2026-11.csv"
print(p)Exercise L11.1 (LO-11.1, ★, about 10 minutes)¶
Without running anything, give:
n1:p.name;n2:p.stem;n3:p.suffix;n4:p.parent.name.q: the path of a file namedsummary.jsonin the same folder asp, built frompwith/, not by typing the folder names again.
n1 = "..."
n2 = "..."
n3 = "..."
n4 = "..."
q = Noneassert n1 == "2026-11.csv", "n1: .name is the last part of the path."
assert n2 == "2026-11", "n2: .stem is the name without its suffix."
assert n3 == ".csv", "n3: .suffix is the extension, dot included."
assert n4 == "harbor", "n4: .parent is the folder that holds the file; take its .name."
assert isinstance(q, Path), "q: build a Path with /, starting from p.parent."
assert q == LAB / "stations" / "harbor" / "summary.json", f"q is {q}, in the wrong folder."
print("passed")2. Text files¶
Exercise L11.2 (LO-11.1, ★★, about 15 minutes)¶
Write three functions for a station’s log, a text file with one entry on each line. Open every
file with encoding="utf-8", in a with statement.
write_log(path, entries)writes each string in the listentrieson a line of its own, replacing anything already in the file.add_entry(path, entry)adds one line at the end of the file, keeping what is there.read_log(path)returns the file’s lines as a list of strings, without their newlines.
Hint
The modes are "w" and "a". Write entry + "\n". To read, loop over the file and append line.rstrip("\n"), or use .splitlines() on the whole text.
def write_log(path, entries):
"""Write each entry on a line of its own, replacing the file's contents."""
...
def add_entry(path, entry):
"""Add entry as a new line at the end of the file."""
...
def read_log(path):
"""Return the file's lines, without their newlines."""
...log = LAB / "log.txt"
write_log(log, ["Nov 2: calm", "Nov 3: gauge cleaned"])
assert read_log(log) == ["Nov 2: calm", "Nov 3: gauge cleaned"], (
f"After write_log, read_log returned {read_log(log)!r}."
)
add_entry(log, "Nov 4: storm at Søndre pier")
assert read_log(log) == ["Nov 2: calm", "Nov 3: gauge cleaned", "Nov 4: storm at Søndre pier"], (
"add_entry should keep the old lines and add one at the end."
)
assert log.read_bytes().count(b"\xc3\xb8") == 1, "Write the file as UTF-8: encoding=\"utf-8\"."
write_log(log, ["Dec 1: new month"])
assert read_log(log) == ["Dec 1: new month"], "write_log should replace what was in the file."
assert log.read_text(encoding="utf-8") == "Dec 1: new month\n", "End every line with \\n."
print("passed")3. Encodings¶
Exercise L11.3 (LO-11.1, ★, about 10 minutes)¶
The cell after the check writes the word Zürich to a file as UTF-8, then reads it back as
cp1252. In UTF-8, each of the letters A to Z takes one byte, and ü takes two, 0xC3 and
0xBC; in cp1252, every byte is one character, and those two bytes are à and ¼. The
cell’s read_bytes() returns the file’s bytes without decoding them, so their len is the
file’s size. Without running the cell, give:
b1: how many bytes the file holds.b2: the string the cell prints.
b1 = 0
b2 = "..."assert b1 == 7, "b1: six characters, five of them one byte each, and ü two."
assert b2 == "Zürich", "b2: each of ü's two bytes becomes one cp1252 character."
print("passed")city = LAB / "city.txt"
city.write_text("Zürich", encoding="utf-8")
print(len(city.read_bytes()), "bytes")
print(city.read_text(encoding="cp1252"))4. Reading a CSV file¶
Run the next cell to see readings.csv, which the setup cell wrote. The first station’s name
has a comma in it, so it is in quotes.
print((LAB / "readings.csv").read_text(encoding="utf-8"))Exercise L11.4 (LO-11.2, ★★, about 15 minutes)¶
Write read_readings(path), which reads a CSV file with the columns station, date,
temp_c, and rain_mm, and returns a list with a dictionary for each row: station and
date as strings, and temp_c and rain_mm as floats. Use csv.DictReader, and open the
file with newline="" and encoding="utf-8".
def read_readings(path):
"""Return the rows of a readings CSV file as dictionaries, with the numbers as floats."""
...readings = read_readings(LAB / "readings.csv")
assert isinstance(readings, list) and len(readings) == 5, (
"Return a list with one dictionary for each of the five rows, without the header."
)
assert readings[0] == {"station": "Harbor, north pier", "date": "2026-11-02", "temp_c": 8.5,
"rain_mm": 0.0}, f"The first row came back as {readings[0]!r}."
assert isinstance(readings[4]["rain_mm"], float), "Convert rain_mm with float."
assert readings[4] == {"station": "Hilltop", "date": "2026-11-03", "temp_c": 7.5,
"rain_mm": 5.5}, f"The last row came back as {readings[4]!r}."
print("passed")5. Writing a CSV file¶
Exercise L11.5 (LO-11.2, ★★, about 15 minutes)¶
Write write_rain_totals(path, readings), which takes a list like the one read_readings
returns and writes a CSV file with a header row, station,total_rain_mm, and then one row for
each station, in alphabetical order, with the total of its rain_mm rounded to 1 decimal place.
Build the totals in a dictionary first, as in Module 8, then write them with csv.writer or
csv.DictWriter, opening the file with newline="" and encoding="utf-8". When the check
passes, it prints the file: see how csv put quotes around the name with a comma in it.
def write_rain_totals(path, readings):
"""Write each station's total rain, alphabetically, to a CSV file at path."""
...totals_path = LAB / "rain_totals.csv"
write_rain_totals(totals_path, read_readings(LAB / "readings.csv"))
assert totals_path.exists(), "write_rain_totals didn't create the file."
with open(totals_path, newline="", encoding="utf-8") as file:
rows = list(csv.reader(file))
assert rows[0] == ["station", "total_rain_mm"], f"The header row is {rows[0]!r}."
assert rows[1:] == [["Harbor, north pier", "14.4"], ["Hilltop", "6.1"]], (
f"The station rows are {rows[1:]!r}."
)
assert b"\r\r\n" not in totals_path.read_bytes(), 'Open the file with newline="".'
print("passed")
print()
print(totals_path.read_text(encoding="utf-8"))6. JSON¶
A station’s details include a tuple, its location, and a set, its sensors:
details = {
"name": "Harbor",
"location": (54.5, -3.2),
"sensors": {"thermometer", "rain gauge", "anemometer"},
}Exercise L11.6 (LO-11.3, ★★, about 15 minutes)¶
Write
save_details(path, details), which saves a dictionary likedetailsas JSON, withindent=2. JSON has no sets, so savesensorsas a list, sorted alphabetically, and leavedetailsitself unchanged.Write
load_details(path), which loads it back and returns the dictionary.Without running anything, give
j1: whatload_details(...)["location"]will be, after a save and a load.
def save_details(path, details):
"""Save details as JSON, with its set of sensors as a sorted list."""
...
def load_details(path):
"""Return the dictionary saved as JSON at path."""
...
j1 = Nonedetails_path = LAB / "details.json"
save_details(details_path, details)
assert isinstance(details["sensors"], set), "Leave details unchanged: make a copy to save."
text = details_path.read_text(encoding="utf-8")
assert json.loads(text)["sensors"] == ["anemometer", "rain gauge", "thermometer"], (
"Save sensors as a list, sorted alphabetically."
)
assert "\n " in text, "Save it with indent=2."
loaded = load_details(details_path)
assert loaded == {"name": "Harbor", "location": [54.5, -3.2],
"sensors": ["anemometer", "rain gauge", "thermometer"]}, (
f"load_details returned {loaded!r}."
)
assert j1 == [54.5, -3.2], "j1: a tuple is saved as a JSON array, which loads as a list."
print("passed")7. Recursion over nested data¶
Run the next cell to see NETWORK, which the setup cell made. Rain readings appear at several
depths: in each station’s readings, and in a backup station inside a station. The contact’s
rain_mm is None, because nobody measured it; JSON writes None as null.
print(json.dumps(NETWORK, indent=2))Exercise L11.7 (LO-11.4, ★★, about 15 minutes)¶
Write
total_rain(data), a recursive function that returns the total of every value stored under the key"rain_mm", at any depth, in nested dictionaries and lists. Skip a value that isNone.total_rain(NETWORK)is 3.8, give or take floating-point rounding.Give
base: which kind of value is the base case, the one where your function returns without calling itself? Answer"dict","list", or"other".
Hint
Follow count_values in the reading. For a dictionary, add the rain_mm value if the key is there and the value isn’t None, then add total_rain of each value. For a list, add total_rain of each item. Anything else adds nothing.
def total_rain(data):
"""Return the total of the values under "rain_mm" anywhere in data, skipping None."""
...
base = "..."assert total_rain(5) == 0 and total_rain("rain_mm") == 0, "A value that isn't a container adds 0."
assert total_rain({"rain_mm": 2.5}) == 2.5, "Count a rain_mm at the top level."
assert total_rain([{"rain_mm": 1.0}, [{"rain_mm": 2.0}]]) == 3.0, "Look inside lists, at any depth."
assert total_rain({"rain_mm": None}) == 0, "Skip a rain_mm whose value is None."
assert abs(total_rain(NETWORK) - 3.8) < 1e-9, f"total_rain(NETWORK) is {total_rain(NETWORK)}."
assert base == "other", "base: lists and dictionaries call total_rain again; other values don't."
print("passed")8. Recursion over folders¶
Run the next cell. It lists every path under scratch/lab11/tree, which the setup cell made,
with rglob, which does the walk for you.
TREE = LAB / "tree"
for path in sorted(TREE.rglob("*")):
print(path.relative_to(TREE).as_posix())relative_to(TREE) gives the part of a path after TREE, and as_posix() writes it with /
on every operating system.
Exercise L11.8 (LO-11.4, ★★★, about 15 minutes)¶
Write find_files(folder, suffix), a recursive function that returns a list of every file under
folder, at any depth, whose suffix is suffix (such as ".csv"), as Path objects. Walk the
folders yourself with iterdir, is_dir, and a call to find_files for each folder inside;
don’t use rglob or os.walk. The order of the list doesn’t matter.
def find_files(folder, suffix):
"""Return every file under folder, at any depth, whose suffix is suffix."""
...found = find_files(TREE, ".csv")
assert isinstance(found, list), "Return a list."
assert all(isinstance(path, Path) for path in found), "Return Path objects, not their names."
names = sorted(path.relative_to(TREE).as_posix() for path in found)
assert names == ["archive/2024/dec.csv", "archive/2025/feb.csv", "archive/2025/jan.csv",
"current/nov.csv"], f"find_files(TREE, '.csv') found {names}."
assert find_files(TREE / "current", ".txt") == [], "A folder with no matching files gives []."
assert sorted(path.name for path in find_files(TREE, ".txt")) == ["notes.txt", "readme.txt"], (
"find_files should work for any suffix."
)
print("passed")Summary¶
In this lab you:
built paths with
/and read their parts with.name,.stem,.suffix, and.parent;wrote, appended to, and read a text file, naming its encoding;
saw UTF-8 bytes read as cp1252 turn one letter into two wrong ones;
read a CSV file into dictionaries with the right types, and wrote a summary CSV file;
saved data with a tuple and a set as JSON, and saw what came back; and
wrote recursive functions that search nested data and a folder tree, and named their base case.
Next, the Module 11 practice has more exercises of each kind.