3.2 — Saving & Loading Files
Keep your data after the program closes, using a JSON file.
Why This Matters
When your program closes, its variables disappear. A file keeps the data between runs. JSON is a text format that stores dictionaries and lists, and Python can read it back into the same shapes.
The Idea
import json
def save_data(data, filename):
with open(filename, "w") as f:
json.dump(data, f, indent=2)
def load_data(filename):
with open(filename) as f:
return json.load(f)
The with block closes the file for you. "w" means write, and it replaces whatever was in the file. So make sure you're saving the whole data set, not just the part that changed.
On the first run there's no file yet, so check before you load:
import os
def load_or_start(filename):
if os.path.exists(filename):
return load_data(filename)
return {} # first run: start with empty data
JSON rules to know: keys are always text (a number key comes back as text), and only dictionaries, lists, text, numbers and true/false/none can be saved directly.
Extended: you can use try and except FileNotFoundError instead of the if check, and json.JSONDecodeError for a damaged file. Either works for the missing-file test.
Try It
- Save a small dictionary to
test.json. - Open
test.jsonin VS Code. Can you read your data? - Load it back and print it. Does it match what you saved?
- Delete
test.jsonand runload_or_start. It should start empty, not crash.
Practice Notebook
Work through more examples, in different contexts, in a Jupyter notebook. Every exercise has a check cell that tells you when your code is right.
How to open it: open the file in VS Code, pick a Python kernel, and run the cells from top to bottom with Shift + Enter.
Common Mistakes
- Opening with
"w"to read. That wipes the file. Use"r"or leave the mode out when you load. - Only saving when the program quits. If it crashes, the work is gone. Save after each change.
- Mixing up
json.dumpandjson.dumps.dumpwrites to a file.dumpsreturns text.
You're Done With This Lesson When…
Data you save comes back exactly the same, and a first run with no file doesn't crash.