Another mission is complete, and every crew member's mission count needs to go up by one. Nova has also earned her place on the crew list at last.
Rocket rubs his hands together. "Load the file, add one to everybody, add Nova, save. Four steps."
Raven raises a finger. "What do you notice if we run it twice by accident?" she asks. "The counts go up twice, which is fair, because two runs means two missions. But Nova would be added twice."
Nova laughs, a soft chime. "Interesting," she says. "Two of me would be confusing. Check whether a name is already on the list before adding it."
Rocket writes a small helper function to look up a crew member by name.
# update_crew.py
import json
def find_member(crew, name):
"""Give back the record with this name, or None."""
for member in crew:
if member["name"] == name:
return member
return None
with open("crew.json") as f:
crew = json.load(f)
for member in crew:
member["missions"] = member["missions"] + 1
if find_member(crew, "Nova") is None:
crew.append({"name": "Nova", "role": "companion", "missions": 1})
with open("crew.json", "w") as f:
json.dump(crew, f, indent=2)
for member in crew:
print(member["name"], member["missions"]) Starting from Tuesday's crew.json, the first run shows:
Rocket 4 Raven 5 Nova 1
The second run loads the updated file. Nova is found, so she is not added again:
Rocket 5 Raven 6 Nova 2
Removing records uses the same pattern. Load the list, build a new list with only the records to keep, then write the new list back.
# clear_done.py
import json
with open("tasks.json") as f:
tasks = json.load(f)
remaining = []
for task in tasks:
if not task["done"]:
remaining.append(task)
with open("tasks.json", "w") as f:
json.dump(remaining, f, indent=2)
print(f"Cleared {len(tasks) - len(remaining)}, kept {len(remaining)}") [
{"name": "Check fuel", "done": true},
{"name": "Check weather", "done": false},
{"name": "Seal doors", "done": true}
] Starting from the tasks.json above, the program shows Cleared 2, kept 1.
| Statement | True or false? |
|---|---|
| Read, change, write back saves the whole list each time. | ? |
| Mode "a" is right for writing back a changed JSON list. | ? |
| A record is often stored as a dictionary. | ? |
| The program changes tasks.json without loading it first. | ? |
Read, change, write back is how real apps update saved data. Tomorrow you will handle the very first run, when there is no file yet.