Show contents
Chapter 5 of 6 · 25 min
Project: a contact book that remembers
By the end of this chapter, you'll be able to
- Design a program around load and save functions
- Validate data with raise before saving it
- Make loading robust against a missing or damaged file
- Export the data as CSV for other software
The specification
The book is a list of dictionaries {"name": ..., "phone": ...}, saved in contacts.json. We need:
load(): returns the saved book, or an empty list the first time the program runs;save(contacts): writes the book as readable JSON;add(contacts, name, phone): refuses an empty name, an invalid number (6 to 15 digits, spaces and a leading+allowed) or a name that's already there;search(contacts, start): returns the contacts whose name starts withstart, ignoring case.
We simulate two runs of the program: the second one reads back what the first one saved.
Version 1: a book that remembers
import json
from pathlib import Path
FILE = Path("contacts.json")
def load(path=FILE):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
return []
def save(contacts, path=FILE):
with open(path, "w", encoding="utf-8") as f:
json.dump(contacts, f, ensure_ascii=False, indent=2)
def add(contacts, name, phone):
name = name.strip()
digits = phone.replace(" ", "").removeprefix("+")
if not name:
raise ValueError("the name is empty")
if not digits.isdigit() or not 6 <= len(digits) <= 15:
raise ValueError(f"invalid number: {phone!r}")
if any(c["name"].lower() == name.lower() for c in contacts):
raise ValueError(f"{name} is already in the book")
contacts.append({"name": name, "phone": phone.strip()})
def search(contacts, start):
start = start.lower()
return [c for c in contacts if c["name"].lower().startswith(start)]
# First run: no file, we start from an empty book.
FILE.unlink(missing_ok=True)
book = load()
for name, phone in [("Fatou", "+221 77 123 45 67"), ("Diego", "0991 234 567"), ("fatou", "0611 22 33 44"), ("Kofi", "12-34")]:
try:
add(book, name, phone)
except ValueError as error:
print("Refused:", error)
save(book)
# Second run: the book is read back from the file.
book = load()
print(len(book), "contacts:", [c["name"] for c in book])
print(search(book, "di"))
Refused: fatou is already in the book
Refused: invalid number: '12-34'
2 contacts: ['Fatou', 'Diego']
[{'name': 'Diego', 'phone': '0991 234 567'}]
A few choices worth noticing:
- Validate before saving.
addraises aValueErrorat the slightest problem. Invalid data never gets into the book, so never into the file. removeprefix("+")removes the+only if it's at the start;isdigit()checks that only digits are left.any(...)returnsTrueas soon as a contact has the same name: it's the duplicate search in one line.- The file's path is a default parameter: your tests can use another file without touching the real book.
On the next run, load() reads the file again: the book has remembered.
Text description of the animation
- First run: FileNotFoundError is caught, we start from an empty list.
- The valid contacts are added to the list, in memory.
- The duplicate is refused before it gets into the list: the file will never see it.
- The list is written as JSON. The program can now stop.
- On the next run, load() reads the file again: the book has remembered.
Version 2: surviving a damaged file
A power cut while writing, a clumsy edit by hand… and contacts.json can end up truncated. json.load then raises a json.JSONDecodeError. Crashing isn't a good answer, and neither is erasing the file: we keep a copy of the original so it can be repaired, and start again from an empty book.
import json
def load(path):
try:
with open(path, encoding="utf-8") as f:
return json.load(f)
except FileNotFoundError:
return []
except json.JSONDecodeError:
with open(path, encoding="utf-8") as f:
damaged = f.read()
with open(path + ".damaged", "w", encoding="utf-8") as f:
f.write(damaged)
print(f"Unreadable file: copy kept in {path}.damaged")
return []
with open("broken_contacts.json", "w", encoding="utf-8") as f:
f.write('[{"name": "Fatou", "phone": ') # file cut off in the middle
print(load("broken_contacts.json"))
Unreadable file: copy kept in broken_contacts.json.damaged
[]
Version 3: exporting and deleting
A CSV export lets you open the book in a spreadsheet. csv.DictWriter writes dictionaries directly, column by column:
import csv
contacts = [
{"name": "Fatou", "phone": "+221 77 123 45 67"},
{"name": "Diego", "phone": "0991 234 567"},
]
def export_csv(contacts, path):
with open(path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["name", "phone"])
writer.writeheader()
writer.writerows(sorted(contacts, key=lambda c: c["name"].lower()))
return len(contacts)
def delete(contacts, name):
for i, c in enumerate(contacts):
if c["name"].lower() == name.lower():
return contacts.pop(i)
raise ValueError(f"no contact named {name!r}")
print(export_csv(contacts, "export.csv"), "contacts exported")
with open("export.csv", encoding="utf-8") as f:
print(f.read(), end="")
print(delete(contacts, "fatou"))
try:
delete(contacts, "Zoé")
except ValueError as error:
print("Refused:", error)
assert [c["name"] for c in contacts] == ["Diego"]
2 contacts exported
name,phone
Diego,0991 234 567
Fatou,+221 77 123 45 67
{'name': 'Fatou', 'phone': '+221 77 123 45 67'}
Refused: no contact named 'Zoé'
enumerate(contacts) gives both the index and the item, and pop(i) removes the item at that index while returning it.
Your turn
Project: complete the contact bookPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Worked exercise: merging two contact books
You have two books (two lists of contacts), for example the one on the phone and the one on the computer. Write merge(a, b) that returns a new book containing all the contacts, with no duplicate name (ignoring case). For a duplicate, keep the version from a. The result is sorted by name, and a and b mustn't be changed.
Hint 1
{lowercase name: contact}: first add the contacts of b, then those of a, which will overwrite the duplicates.Hint 2
sorted(d.values(), key=lambda c: c["name"].lower()) returns a new sorted list.Show the solution and common mistakes
def merge(a, b):
by_name = {}
for contact in b + a:
by_name[contact["name"].lower()] = contact
return sorted(by_name.values(), key=lambda c: c["name"].lower())
phone = [{"name": "Fatou", "phone": "+221 77 123 45 67"}, {"name": "Ana", "phone": "912 345 678"}]
computer = [{"name": "fatou", "phone": "0000 000"}, {"name": "Wei", "phone": "138 0013 8000"}]
result = merge(phone, computer)
for c in result:
print(c["name"], c["phone"])
assert len(phone) == 2 and len(computer) == 2
Ana 912 345 678
Fatou +221 77 123 45 67
Wei 138 0013 8000
b + a creates a new list: the contacts of b first, then those of a. Since a comes last, its contacts overwrite those of b in the dictionary.
Common mistakes:
- Doing
a.extend(b): the caller's listais changed, when we asked for a new book. - Comparing names without
lower(): "Fatou" and "fatou" would stay two separate contacts.
Summary
- 1A program that remembers revolves around two functions: load and save.
- 2Each piece of data is validated with raise before it reaches the file.
- 3Loading handles the first run (FileNotFoundError) and the damaged file (JSONDecodeError).
- 4Changes live in memory until you save.
- 5A CSV export opens your data to any spreadsheet.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.