Sub topic 7
Saving and loading your data
This chapter makes the habit log survive between runs. It assumes you can write basic Python functions, use dictionaries and sets, and read and write text files. It also assumes you know datetime.date. The log from the earlier chapters is a dictionary that maps each habit name to a set of dates. It lives only in memory, so it disappears when the program exits.
Why JSON
JSON is a text format for nested data. It supports objects, lists, strings, numbers, booleans and null. It suits this tracker for three reasons:
- It ships with Python in the
jsonmodule. - You can open and edit the file in any text editor.
- It maps directly onto dictionaries and lists.
JSON has no date type and no set type. Calling json.dumps on a date or a set raises a TypeError. You have to convert them yourself, in both directions.
Choosing a file format for dates
Store each date as an ISO 8601 string, such as "2026-11-27". Python's date.isoformat() produces it, and date.fromisoformat() reads it back. ISO strings have two useful properties:
- They sort alphabetically in the same order as chronologically.
- They are unambiguous.
03/04/2026could mean March 4 or April 3, but2026-04-03cannot be misread.
Store each habit's dates as a sorted list. A set has no order, so sorting keeps the file stable. When you save the same data twice, you get identical output, which keeps diffs readable if you put the file under version control.
The file on disk looks like this:
{
"read": ["2026-11-25", "2026-11-26", "2026-11-27"],
"run": ["2026-11-24", "2026-11-26"]
}The conversion
Here are the two functions.
import json
from datetime import date
from pathlib import Path
def save(log, path="habits.json"):
data = {name: sorted(d.isoformat() for d in days) for name, days in log.items()}
Path(path).write_text(json.dumps(data, indent=2))
def load(path="habits.json"):
p = Path(path)
if not p.exists():
return {}
data = json.loads(p.read_text())
return {name: {date.fromisoformat(s) for s in days} for name, days in data.items()}In save, a dictionary comprehension builds a new dictionary. Each set of dates becomes a sorted list of strings. Sorting the date objects and sorting the ISO strings give the same order, so sorting the strings is safe. indent=2 makes the file readable.
In load, a missing file returns an empty log. This handles the first run, when nothing has been saved yet. Each list of strings becomes a set of dates. Because the result is a set, a duplicate date in the file collapses to one entry, which matches the rule from the check-in chapter.
A round trip
Test the two functions together. Whatever you save should come back unchanged.
from datetime import date
log = {"read": {date(2026, 11, 26), date(2026, 11, 27)}}
save(log, "test_habits.json")
assert load("test_habits.json") == log
print("round trip ok")Comparing the loaded log to the original with == checks both the keys and the sets of dates. A round-trip test like this catches most mistakes in a save and load pair.
Using it in a session
The usual pattern is to load once at the start, change the log in memory, and save after each change:
log = load()
check_in("read") # from the earlier chapter, updates the in-memory logcheck_in as defined earlier writes to a module-level log, so a script that does log = load() at module level will share it. Call save(log) after the check-in so the change reaches the disk.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: Object of type date is not JSON serializable` | A `date` or `set` was passed straight to `json.dumps`. | Convert with `isoformat()` and `sorted()` first. |
| `ValueError: Invalid isoformat string` on load | The file was edited by hand and a date is malformed. | Fix the date to `YYYY-MM-DD`. |
| `json.JSONDecodeError` on load | The file is empty or truncated, often after a crash during writing. | Restore the file, or delete it to start fresh. |
| Check-ins vanish after a run | `save` was never called after the change. | Call `save(log)` after each change. |
Exercises
Exercise
Why does save use sorted(...) on each habit's dates instead of list(...)?
Show answer
A set has no defined order, so list could produce a different order each time. Sorting gives the same file for the same data. It also keeps the dates in chronological order, because ISO strings sort the same way as the dates they represent.
Exercise
Write a function save_atomic(log, path="habits.json") that avoids leaving a half-written file. Use the save function from this chapter.
Show answer
Write to a temporary path, then replace the real file.
from pathlib import Path
def save_atomic(log, path="habits.json"):
tmp = path + ".tmp"
save(log, tmp)
Path(tmp).replace(path)
If the program stops during save, only the .tmp file is damaged. The replace step swaps the files in one operation, so habits.json is always complete.