Lesson 9.9
Let's build a diary: read the old notes from a JSON file, add a new one and save everything back.
import json
from pathlib import Path
file = Path("notes.json")
if file.exists():
with open(file, encoding="utf-8") as f:
notes = json.load(f)
else:
notes = []
notes.append("Buy a notebook")
with open(file, "w", encoding="utf-8") as f:
json.dump(notes, f, indent=2, ensure_ascii=False)
# In this task the file already exists: the else branch is not needed.
The check sets the file name filename, the old notes old and the new one new_note.
Read the old notes (the file already exists), add the new one, save it and print
everything as <number>. <note>, one line per entry.
Three steps: read the file, change the list, write it back.
json.load gives the list of notes, append adds the new one, json.dump
saves it back with indent=2 and ensure_ascii=False.
Number the lines when printing with enumerate(notes, start=1).