Sub topic 7
Saving and loading your data
This chapter assumes you can write Python functions and work with dictionaries and sets. It also assumes you know date and timedelta from the datetime module and can read and write text files. You should also have the log structure from the earlier chapters: a dictionary that maps each habit name to a set of dates.
Why the log must leave memory
Every function so far works on log, which lives in memory. When the program exits, the check-ins disappear. A streak counter that forgets everything overnight has no use, so the tracker needs persistence. Persistence means writing data to storage so that a later run can read it back.
This chapter covers three things:
- Choosing a file format.
- Converting
dateobjects to and from that format. - Handling the failures that file storage brings: a missing file, a damaged file, and a crash in the middle of a write.
Choosing a format
Your data is small: a few habits, each with at most a few hundred dates. Any simple text format works. JSON fits for these reasons:
- It ships with Python in the
jsonmodule, so there is nothing to install. - You can open the file in an editor and read or fix it by hand.
- It maps directly to dictionaries and lists.
- Version control and diff tools show a readable change when you add a check-in.
JSON does not cover everything you use. It has objects (dictionaries with string keys), arrays, strings, numbers, booleans and null. It has no date type and no set type. Your log contains both, so you must convert before saving and convert back after loading.
| In memory | In the JSON file | Conversion |
|---|---|---|
| `dict` of habit name to set | object of habit name to array | build a new dictionary |
| `set` of dates | array of strings | `sorted(...)` to get a list |
| `date(2026, 11, 27)` | `"2026-11-27"` | `isoformat()` and `date.fromisoformat()` |
Why ISO 8601 strings
ISO 8601 is the international date format YYYY-MM-DD. It is a good storage choice for three reasons:
- It is unambiguous.
03/04/2026can mean 3 April or 4 March.2026-04-03has only one reading. - It sorts correctly as text. Sorting the strings alphabetically gives chronological order, so the file stays ordered without extra work.
- Python supports it directly.
date.isoformat()writes it, anddate.fromisoformat()reads it.
Avoid str(date) or strftime with a custom format for storage. A custom format gives you a second format to keep in sync, and it fails silently when someone edits the file.
Saving
The save function builds a plain dictionary of lists of strings, then writes it as JSON.
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))Two details matter here:
sorted(...)does two jobs. JSON cannot store a set, and a list is the closest match. Sorting also makes the output deterministic. Sets have no guaranteed order, so without sorting the same data could produce different files on different runs, and the diffs would be noisy.indent=2makes the file readable. The cost is a slightly larger file, which does not matter at this scale.
Loading
The load function reverses the conversion. A missing file means this is the first run, so it returns an empty log.
import json
from datetime import date
from pathlib import Path
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()}The set comprehension on the last line also removes any duplicate strings that someone typed into the file by hand. This keeps the "one check-in per day" rule intact after loading.
A round trip
A good test for any save and load pair is the round trip. Save a value, load it back, and check that you get an equal value.
from datetime import date
from pathlib import Path
log = {"read": {date(2026, 11, 25), date(2026, 11, 26)}}
save(log, "habits.json")
print(Path("habits.json").read_text())
assert load("habits.json") == log
print("round trip ok")This assumes save and load from above are defined in the same file or imported. The printed file looks like this:
{
"read": [
"2026-11-25",
"2026-11-26"
]
}The assert compares dictionaries of sets of dates, and Python compares those by value. If a later change to your code breaks the conversion, this check fails right away.
The next diagram shows where saving and loading sit in one run of the tracker.
What goes wrong
Most persistence bugs fall into a few groups. Learn to recognize them from the error message.
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError: Object of type set is not JSON serializable` | You passed `log` straight to `json.dumps` | Convert each set to a sorted list first |
| `TypeError: Object of type date is not JSON serializable` | A `date` object is still inside the data | Convert with `isoformat()` |
| `json.JSONDecodeError` on load | The file is empty, truncated or hand-edited with a typo | Report it and stop. Do not continue with an empty log |
| `ValueError: Invalid isoformat string` | A date string is malformed, for example `2026-11-3` | Fix the entry in the file |
| Habit data vanishes after a run | The program loaded `{}` after an error and then saved over the real file | Never treat a damaged file as a missing one |
| Streaks differ between runs | Dates were saved in a different format or time zone | Store plain calendar dates only |
The fifth row is the most dangerous because it loses data without any error.
Failing loudly on a damaged file
A safer load separates the two cases. A missing file gives an empty log. A damaged file raises an error with a message that names the file and the problem.
import json
from datetime import date
from pathlib import Path
def load(path="habits.json"):
p = Path(path)
if not p.exists():
return {}
try:
data = json.loads(p.read_text(encoding="utf-8"))
return {
name: {date.fromisoformat(s) for s in days}
for name, days in data.items()
}
except (json.JSONDecodeError, ValueError, AttributeError, TypeError) as err:
raise ValueError(f"Cannot read {p}: {err}") from errjson.JSONDecodeError is a subclass of ValueError, and so is the error from a bad date string. The tuple lists them anyway so the intent is clear. AttributeError and TypeError cover a file that is valid JSON but has the wrong shape, for example a top-level list instead of an object, or a number in place of a list of dates. The from err part keeps the original error attached, so the traceback shows both.
The explicit encoding="utf-8" matters if habit names contain non-ASCII characters such as "méditer". Without it, Python uses the platform default encoding, and the same file can read differently on two machines. Use the same encoding when you write.
Writing safely
There is a second risk on the save side. write_text opens the file and truncates it to zero length before writing the new content. If the program or the computer stops during the write, you are left with a half-written file. The next load then fails with a JSONDecodeError, and the old data is already gone.
The standard fix is an atomic write. Write the new content to a temporary file in the same directory, then replace the real file in one step. os.replace is atomic on the same filesystem: readers see either the complete old file or the complete new file, never a partial one.
import json
import os
import tempfile
from pathlib import Path
def save(log, path="habits.json"):
target = Path(path)
data = {name: sorted(d.isoformat() for d in days) for name, days in log.items()}
fd, tmp = tempfile.mkstemp(dir=target.parent, suffix=".tmp")
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp, target)
except BaseException:
Path(tmp).unlink(missing_ok=True)
raiseThe steps are:
mkstempcreates a uniquely named temporary file next to the target and returns an open file descriptor and its path. It must be in the same directory so that the replace stays on one filesystem.- The data is written, flushed from Python's buffer, and
fsyncasks the operating system to push it to disk. os.replaceswaps the temporary file into place.- If anything fails, the temporary file is removed and the original error is raised again. The real file is untouched.
Design decisions to know about
Load once, save after each change
Load the file at the start of a command and save it after every change. A command-line tool runs for a fraction of a second, so there is no benefit in keeping state in memory across commands. Saving after each change means a crash loses at most the command that was running.
Where the file lives
A relative path like "habits.json" resolves against the current working directory. If you run the tracker from two different folders, you will get two separate data files, and your streak will seem to reset. For a personal tool, a fixed location is more reliable. One option is Path.home() / ".habits.json". You can also let the user override the path with a command-line option, which the next chapter adds.
Two processes at once
This design does not handle two copies of the program writing at the same time. Each loads the file, changes its own copy, and saves, so the later save overwrites the earlier one. For a single-user tracker this is acceptable. If you ever need concurrent access, use a database such as SQLite, which handles locking for you.
Changing the format later
If you later add fields, such as a target number of days per week, the flat structure of habit name to list of dates no longer fits. Plan for this by keeping the loading code in one place. Then you can change the file format by editing save and load only. The rest of the tracker works with the in-memory dictionary of sets and does not need to know how it is stored.
Exercises
Exercise
A teammate wants to simplify save to Path(path).write_text(json.dumps(log)). Name the error this raises, and give the smallest change that makes the data serializable.
Show answer
It raises TypeError: Object of type set is not JSON serializable, because the values of log are sets (and date objects inside them would fail too). The fix is to convert each set to a list of ISO strings before dumping, for example {name: sorted(d.isoformat() for d in days) for name, days in log.items()}. Sorting also gives a stable file.
Exercise
Your load catches json.JSONDecodeError and returns {}. A user's file is cut off by a power failure, and they then run habit check read. What happens to their old data, and how do you prevent it?
Show answer
load returns an empty log, the new check-in is added to it, and save overwrites the damaged file with one containing a single date. The recoverable old check-ins are lost. To prevent it, raise a clear error when the file exists but cannot be parsed, so the program stops before saving. Using an atomic write on the save side also makes a cut-off file much less likely.
Exercise
Why does the atomic save create the temporary file in target.parent rather than in the system temp directory?
Show answer
os.replace is only atomic when the source and destination are on the same filesystem. The system temp directory is often on a different filesystem, where the replace could fall back to a copy and lose the atomic guarantee, or fail. Creating the temporary file next to the target avoids this.