Objectives: LO-11.1, LO-11.2, LO-11.3, LO-11.4
Prerequisites: Module 8 and
Module 9
Time: about 5.5 hours: 2 for this reading, 2 for Lab 11, and 1.5 for the
practice
Until now, every program’s data has lived in its variables, and vanished when it stopped. This module saves data to files and reads it back: plain text, CSV (the tables that spreadsheets export), and JSON (nested data, the format most web services use). It also teaches recursion, a way to write a function that handles data nested to any depth, such as a JSON document or a folder full of folders. The running example is a weather station’s readings, the kind of data Project 2 works with.
Paths¶
A file’s path says where it is: a list of folder names and then the file’s name. Windows
separates the names with \ and macOS and Linux with /, so a program that builds paths by
joining strings works on only some computers. The standard library’s pathlib module builds them
for you. Its Path type joins names with /, whatever the operating system:
from pathlib import Path
folder = Path("weather")
notes = folder / "notes.txt"
print(notes)
print(notes.name, notes.stem, notes.suffix)
print(notes.parent)weather/notes.txt
notes.txt notes .txt
weatherOn Windows, the first line is weather\notes.txt: Path uses the computer’s own separator when
it prints. .name is the last part, .stem is the name without its suffix (the extension,
such as .txt), and .parent is the folder that holds it.
weather/notes.txt is a relative path, which is relative to the current working directory:
the folder your terminal was in when you started Python, or, in JupyterLab, the notebook’s
folder. Path.cwd() returns it. A script that should find a file beside itself, wherever the
terminal is, starts from its own path, which Python stores in the variable __file__:
data_folder = Path(__file__).parent / "data"Path objects also answer questions about the file system and change it:
| Code | What it does |
|---|---|
path.exists(), path.is_file(), path.is_dir() | Whether something is there, and whether it’s a file or a folder |
folder.mkdir(parents=True, exist_ok=True) | Make the folder, and any missing folders above it; do nothing if it exists |
folder.iterdir() | Each file and folder inside folder, as Path objects, in no set order |
folder.glob("*.csv") | Each path inside folder whose name matches the pattern |
path.stat().st_size | The file’s size in bytes |
Make the example’s folder before you write anything into it:
folder.mkdir(exist_ok=True)
print(folder.is_dir())TrueText files¶
Writing and reading¶
open opens a file and returns a file object, which reads or writes it. Use it in a with
statement, which closes the file when the block ends, even if an error stops the block early.
Until a file is closed, what you wrote may not have reached the disk.
with open(notes, "w", encoding="utf-8") as file:
file.write("Harbor station notes\n")
file.write("Nov 3: cleaned the rain gauge\n")"w" is the mode: write. file.write writes exactly the text you give it, so each line ends
with \n only if you put one there. To read, open the file with mode "r", which is the
default, and loop over it; each line comes with its \n:
with open(notes, encoding="utf-8") as file:
for line in file:
print(repr(line))'Harbor station notes\n'
'Nov 3: cleaned the rain gauge\n'line.rstrip("\n") removes the newline when you don’t want it. file.read() returns the whole
file as one string instead. The four modes you’ll use:
| Mode | Opens the file to | If the file exists | If it doesn’t |
|---|---|---|---|
"r" | Read (the default) | Reads it | FileNotFoundError |
"w" | Write | Empties it first | Creates it |
"a" | Append: write at the end | Keeps what’s there | Creates it |
"x" | Write a new file | FileExistsError | Creates it |
"a" adds a line without losing the others:
with open(notes, "a", encoding="utf-8") as file:
file.write("Nov 4: heavy rain\n")
print(notes.read_text(encoding="utf-8"))Harbor station notes
Nov 3: cleaned the rain gauge
Nov 4: heavy rain
read_text and write_text are Path shortcuts that open the file, read or write all of it,
and close it, in one call. notes.read_text(encoding="utf-8").splitlines() gives a list of the
lines without their newlines.
Encodings¶
A file holds bytes, not characters. An encoding is the rule that turns characters into bytes
and back. UTF-8 can encode every character in Unicode, from é to € to 日, and it is the
encoding of almost every web page and of JSON. Some computers use another one by default, such as
Windows’ cp1252 (also called Windows-1252). Reading a file with the wrong encoding gives wrong
characters, or an error:
menu = folder / "menu.txt"
menu.write_text("Café opens at 7\n", encoding="utf-8")
print(menu.read_text(encoding="cp1252"))Café opens at 7
UTF-8 stores é as two bytes, and cp1252 reads them as two characters, Ã and ©. Without
encoding, open used the computer’s own default up to Python 3.14, which on Windows is often not
UTF-8; from Python 3.15, the default is UTF-8 everywhere (PEP
686). Name the encoding anyway, as the Python tutorial
recommends: then the program reads and writes the same bytes on every computer and every Python
version. This course always writes encoding="utf-8".
CSV files¶
A CSV file (comma-separated values) is a table in plain text: one row on each line, with commas between the fields, and usually a header row of column names first. Here are three days of readings from the station:
date,temp_c,rain_mm
2026-11-02,8.5,0.0
2026-11-03,11.0,2.4
2026-11-04,6.5,12.0Splitting each line at its commas works until a field has a comma in it, such as
Harbor, north pier. CSV puts such a field in double quotes, and the standard library’s csv
module handles that, and the other rules, for you.
Writing a CSV file¶
csv.writer writes lists as rows:
import csv
rows = [
["date", "temp_c", "rain_mm"],
["2026-11-02", 8.5, 0.0],
["2026-11-03", 11.0, 2.4],
["2026-11-04", 6.5, 12.0],
]
readings_path = folder / "readings.csv"
with open(readings_path, "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(rows)Open a CSV file with newline="", for reading and for writing. The csv module handles the
ends of lines itself, and the csv documentation
warns that without newline="", a line break inside a quoted field is misread, and on Windows
each row gets an extra \r, which many spreadsheets show as a blank row.
writer.writerow(row) writes one row. Numbers are written as text, and a field with a comma or
a quote gets quotes:
import io
buffer = io.StringIO()
csv.writer(buffer).writerow(["Harbor, north pier", 8.5])
print(repr(buffer.getvalue()))'"Harbor, north pier",8.5\r\n'(io.StringIO is a file object that keeps its text in memory, which is handy for seeing what a
writer would write.) The row ends with \r\n on every operating system: that is the csv
module’s default, which follows the CSV standard.
Reading a CSV file¶
csv.reader gives each row as a list of strings:
with open(readings_path, newline="", encoding="utf-8") as file:
for row in csv.reader(file):
print(row)['date', 'temp_c', 'rain_mm']
['2026-11-02', '8.5', '0.0']
['2026-11-03', '11.0', '2.4']
['2026-11-04', '6.5', '12.0']Every field is a string, '8.5' included: a CSV file doesn’t record types. Convert each field
yourself, as you converted the text from input. csv.DictReader reads the header for you and
gives each row as a dictionary, keyed by the column names, which makes the conversion read
clearly:
readings = []
with open(readings_path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
readings.append({
"date": row["date"],
"temp_c": float(row["temp_c"]),
"rain_mm": float(row["rain_mm"]),
})
print(readings[0])
print("Total rain:", sum([reading["rain_mm"] for reading in readings]), "mm"){'date': '2026-11-02', 'temp_c': 8.5, 'rain_mm': 0.0}
Total rain: 14.4 mmThe result is a list of records, the nested data of Module 8. csv.DictWriter writes such a
list back: give it the column names, call writeheader, then writerows.
summary_path = folder / "summary.csv"
with open(summary_path, "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["date", "temp_c", "rain_mm"])
writer.writeheader()
writer.writerows(readings)
print(summary_path.read_text(encoding="utf-8").splitlines()[1])2026-11-02,8.5,0.0JSON files¶
JSON (JavaScript Object Notation) stores nested data as text: objects, which are like
dictionaries, and arrays, which are like lists, nested inside each other to any depth. It is the
format of most web services’ answers and of many settings files. The json module converts
between JSON text and Python’s dictionaries and lists. json.dumps turns a value into a JSON
string, and indent lays it out for people:
import json
station = {
"name": "Harbor",
"location": {"lat": 54.5, "lon": -3.2},
"sensors": ["thermometer", "rain gauge"],
"active": True,
"elevation_m": None,
}
print(json.dumps(station, indent=2)){
"name": "Harbor",
"location": {
"lat": 54.5,
"lon": -3.2
},
"sensors": [
"thermometer",
"rain gauge"
],
"active": true,
"elevation_m": null
}json.dump and json.load (without the s) write to and read from a file:
station_path = folder / "station.json"
with open(station_path, "w", encoding="utf-8") as file:
json.dump(station, file, indent=2)
with open(station_path, encoding="utf-8") as file:
loaded = json.load(file)
print(loaded == station, loaded["location"]["lat"])True 54.5JSON looks like Python, but it has its own rules, and some Python values change on the way through:
| Python | JSON | Note |
|---|---|---|
dict | object | Keys become strings: {1: "a"} comes back as {"1": "a"} |
list, tuple | array | A tuple comes back as a list |
str | string | Always in double quotes; single quotes aren’t JSON |
int, float | number | |
True, False | true, false | Lowercase |
None | null | |
set, date, and other types | (none) | json.dumps raises TypeError |
print(json.dumps({1: "a", "pair": (1, 2)}))
print(json.loads('{"1": "a", "pair": [1, 2]}')){"1": "a", "pair": [1, 2]}
{'1': 'a', 'pair': [1, 2]}To save a set, convert it to a sorted list first; to save a date, save the string that
date.isoformat() returns. Text that breaks JSON’s rules, such as {'a': 1} with single quotes,
makes json.loads raise json.JSONDecodeError. Module 12 shows how to report that error kindly
instead of crashing.
Recursion¶
JSON can nest to any depth, and so can folders. A loop handles one level; to handle every level, a function can call itself on each part that is itself nested. A function that calls itself is recursive.
Counting the values in nested data¶
This function counts the values in nested data that aren’t lists or dictionaries: in station,
the name, the two coordinates, the two sensors, True, and None, which makes 7. isinstance(x, dict) is True when x is a dictionary, and works like type(x) == dict.
def count_values(data):
"""Return how many values inside data aren't lists or dictionaries."""
if isinstance(data, dict):
total = 0
for value in data.values():
total = total + count_values(value)
return total
if isinstance(data, list):
total = 0
for item in data:
total = total + count_values(item)
return total
return 1
print(count_values(station))
print(count_values([1, [2, [3, [4]]]]))
print(count_values(5))7
4
1Every recursive function has two kinds of case:
The base case is the answer the function gives without calling itself. Here it is the last line: a value that isn’t a list or a dictionary counts as 1.
The recursive case calls the function on smaller parts and combines their answers. Here a dictionary or a list adds up the counts of its values or items.
Each call works on a part that is nested one level less, so every chain of calls reaches the base
case and stops. This table traces count_values([1, [2]]):
| Call | Case | Returns |
|---|---|---|
count_values([1, [2]]) | List: adds the counts of 1 and [2] | 1 + 1 = 2 |
count_values(1) | Base case | 1 |
count_values([2]) | List: adds the count of 2 | 1 |
count_values(2) | Base case | 1 |
Python keeps every call that hasn’t returned yet, and stops a program that has more than 1,000 of
them at once (the default recursion limit) with RecursionError: maximum recursion depth exceeded. That error almost always means a base case is missing or never reached: a function
that calls itself on the same data, not on a smaller part of it, never stops.
Walking a folder¶
A folder holds files and other folders, which hold more of each, so a folder is nested data too. This function adds up the sizes of all the files in a folder and every folder inside it:
def total_size(folder):
"""Return the total size, in bytes, of the files in folder and in every folder inside it."""
total = 0
for path in folder.iterdir():
if path.is_dir():
total = total + total_size(path)
else:
total = total + path.stat().st_size
return total
archive = folder / "archive" / "2025"
archive.mkdir(parents=True, exist_ok=True)
(archive / "old.txt").write_text("Old readings\n", encoding="utf-8")
print(total_size(folder))438The base case is a file, whose size is its answer, and a folder with no folders inside it ends
the chain of calls. The total is the six files this module has written: 69 bytes of notes, 17 of
menu (é takes two bytes in UTF-8), 83 each for the two CSV files, 173 of station data, and 13
in the archive. On Windows, the total is a little larger: there, a file opened in text mode ends
each line with two characters, \r\n, instead of one. (The CSV files have \r\n everywhere.)
The standard library already walks folders for you: folder.rglob("*") gives every path inside a
folder, at every depth. Recursion is how such functions work, and the way to handle nested data
that no library function knows about, such as the JSON a web service sends.
Common misconceptions¶
| Belief | What happens | Example that breaks it |
|---|---|---|
| A relative path is relative to the script’s folder | It is relative to the current working directory | python m11/report.py, run from py101, looks for data.csv in py101 |
Mode "w" adds to a file | "w" empties the file first; "a" adds | Writing one line with "w" to a 100-line file leaves one line |
Leaving out encoding is fine, because it works on your computer | The default differs between computers and Python versions | A UTF-8 file read as cp1252 shows Café |
csv.reader gives numbers | Every field is a string | "8.5" + "2.4" is "8.52.4" |
| JSON is Python syntax | JSON has its own rules | json.loads("{'a': 1}") raises JSONDecodeError, and True is true |
| JSON keeps every Python type | Tuples become lists, keys become strings, and sets can’t be saved | json.loads(json.dumps({1: (2, 3)})) is {'1': [2, 3]} |
| A recursive function stops by itself | It stops only at a base case that every call reaches | A count_values that calls count_values(data) on the whole list again raises RecursionError |
Summary¶
pathlib.Pathbuilds paths with/that work on every operating system. A relative path is relative to the current working directory;Path(__file__).parentis the script’s folder.Open files in a
withstatement, with a mode ("r","w","a", or"x") andencoding="utf-8"."w"empties a file first.The
csvmodule reads and writes tables, quoting fields that need it. Open CSV files withnewline="", and convert every field from a string yourself.DictReaderandDictWriterwork with rows as dictionaries.The
jsonmodule converts between JSON text and nested dictionaries and lists, withdump/loadfor files anddumps/loadsfor strings. Tuples come back as lists and keys as strings, and sets and dates must be converted first.A recursive function calls itself on smaller parts of its input. Its base case answers without a call; every chain of calls must reach one, or Python stops with
RecursionError.
Self-check¶
Answer each question before you open its answer.
Your terminal is in
py101, and you runpython m11/report.py.report.pyopensPath("data.csv"). Where does Python look for the file, and how do you make it look inm11?Answer
In
py101, the current working directory.Path(__file__).parent / "data.csv"looks in the script’s own folder,m11, wherever the terminal is.What does this print, and why?
with open("log.txt", "w", encoding="utf-8") as file: file.write("one\n") with open("log.txt", "w", encoding="utf-8") as file: file.write("two\n") print(Path("log.txt").read_text(encoding="utf-8"))Answer
twoand a blank line. The secondopenwith"w"empties the file before writing. Mode"a"would keeponeand addtwoafter it.A CSV row is read as
['Oslo', '-3.5', '12']. Write the line that turns it into('Oslo', -3.5, 12).Answer
row = (row[0], float(row[1]), int(row[2])), or with unpacking,city, temp, rain = rowand then(city, float(temp), int(rain)).What is
json.loads(json.dumps({"days": ("Mon", "Tue"), 7: True}))?Answer
{'days': ['Mon', 'Tue'], '7': True}. The tuple became a JSON array and comes back as a list, and the key7became the string"7".This function should return the deepest level of nesting in a list: 0 for a value that isn’t a list, and 1 more than its deepest item for a list. Name its base case, and find the bug.
def depth(data): if isinstance(data, list): deepest = 0 for item in data: deepest = max(deepest, depth(data)) return deepest + 1 return 0Answer
The base case is
return 0, for a value that isn’t a list. The bug isdepth(data), which calls the function on the same list again instead of onitem, so it never reaches the base case and raisesRecursionErrorfor any non-empty list. Withdepth(item),depth([1, [2, [3]]])is 3.
Further reading¶
The Python Tutorial, section 7.2, Reading and Writing Files, including 7.2.2, on saving structured data with
json.The Python documentation for
pathlib,csv, andjson. Each page lists every function this module skipped, with examples.Al Sweigart, Automate the Boring Stuff with Python, 3rd edition, chapter 10, Reading and Writing Files, and chapter 18, CSV, JSON, and XML Files. More practice with the same modules, on everyday tasks.
Allen B. Downey, Think Python, 3rd edition, chapter 5, Conditionals and Recursion. Recursion from the beginning, with stack diagrams that show each call waiting for the one below it.