§ 1.8section 8 of 16·~6 min
Reading and writing files (JSON)
Variables vanish when the program ends. To remember expenses between runs, save them to a file. JSON is the standard text format for this, and it's the same format that APIs and LLMs speak.
import json
from pathlib import Path
DATA_FILE = Path("expenses.json")
expenses = [{"amount": 250.0, "category": "food", "note": "chai"}]
# write: Python list → JSON text → file
DATA_FILE.write_text(json.dumps(expenses, indent=2, ensure_ascii=False))
# read: file → JSON text → Python list
if DATA_FILE.exists():
loaded = json.loads(DATA_FILE.read_text())
else:
loaded = []
json.dumpsturns Python into a JSON string, andjson.loadsturns a JSON string back into Python. (Thesstands for string.)indent=2makes the file readable to humans.ensure_ascii=Falsekeeps₹and Hindi text readable instead of turning them into₹.Path(...).exists()checks for the file so the first run doesn't crash.
This is what expenses.json looks like:
[
{
"amount": 250.0,
"category": "food",
"note": "chai"
}
]
JSON's types map directly to Python's: object ↔ dict, array ↔ list, string ↔ str, number ↔ int/float, true/false ↔ True/False, null ↔ None.
The other way to use files is open() with a with block, which closes the file for you automatically:
with open("expenses.json", "w", encoding="utf-8") as f:
json.dump(expenses, f, indent=2)
with open("expenses.json", encoding="utf-8") as f:
expenses = json.load(f)