Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Lab 11: Files and data formats

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.

1. Paths

Run the next cell. It builds a path from four parts, and prints it.

Exercise L11.1 (LO-11.1, ★, about 10 minutes)

Without running anything, give:

  1. n1: p.name; n2: p.stem; n3: p.suffix; n4: p.parent.name.

  2. q: the path of a file named summary.json in the same folder as p, built from p with /, not by typing the folder names again.

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 list entries on 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.

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:

  1. b1: how many bytes the file holds.

  2. b2: the string the cell prints.

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.

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".

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.

6. JSON

A station’s details include a tuple, its location, and a set, its sensors:

Exercise L11.6 (LO-11.3, ★★, about 15 minutes)

  1. Write save_details(path, details), which saves a dictionary like details as JSON, with indent=2. JSON has no sets, so save sensors as a list, sorted alphabetically, and leave details itself unchanged.

  2. Write load_details(path), which loads it back and returns the dictionary.

  3. Without running anything, give j1: what load_details(...)["location"] will be, after a save and a load.

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.

Exercise L11.7 (LO-11.4, ★★, about 15 minutes)

  1. 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 is None. total_rain(NETWORK) is 3.8, give or take floating-point rounding.

  2. 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.

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.

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.

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.