Python todo notebook (5/6): persistence
Save the todo notebook after each change or only on exit, recover from a broken JSON file, and keep an optional backup copy before you overwrite it.
Getting started
Home Assistant
Buying
Save the todo notebook after each change or only on exit, recover from a broken JSON file, and keep an optional backup copy before you overwrite it.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
Without a save, closing the terminal throws the work away. Two common strategies:
sauvegarder(chemin, data). Simple, and you keep the data if the program crashes.For a small notebook, saving often is not a problem.
def avec_sauvegarde(chemin, data, fonction, *args):
ok = fonction(data, *args)
if ok:
sauvegarder(chemin, data)
return ok
Or call sauvegarder yourself after each menu branch that changes data.
import json
def charger_securise(chemin):
try:
return charger(chemin)
except json.JSONDecodeError:
print("Unreadable JSON file — starting empty. Save the old file first if you need it.")
return {"prochain_id": 1, "taches": []}
Renaming taches.json to taches.json.broken before you overwrite it can help the person using the program.
Before you write, copy taches.json to taches.json.bak with shutil.copy2. That helps if the program is interrupted during the write. With small files, that interruption is rare.
sauvegarder has succeeded.python todo.py --dry-run (show the notebook, do not save).Part 6 — Put the project together: main() and extensions.
A book search for Python and JSON data: Check today’s price on Amazon.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).