Due 12/16 at 11:59pm
In this project, you will extend Contact Book (Part 1) to save and load contacts from a file. Your contact data will now persist between program runs.
Your program must meet the following specifications:
For example:
=== Contact Book ===
Loaded 2 contacts from file.
Contact Book Menu
1. Add contact
2. View all contacts
3. Search for contact
4. Delete contact
5. Quit
Choice: 1
Enter name: Bob
Enter phone: 555-5678
Enter email: [email protected]
Enter address: 456 Oak St
Contact saved!
Choice: 5
Saving contacts to file...
Goodbye!
The contacts.json file would contain:
{
"Alice": {"phone": "555-1234", "email": "[email protected]", "address": "123 Main St"},
"Bob": {"phone": "555-5678", "email": "[email protected]", "address": "456 Oak St"}
}
You can read a JSON file:
import json
with open("contacts.json", "r") as file:
contacts = json.load(file)
You can write a JSON file:
import json
with open("contacts.json", "w") as file:
json.dump(contacts, file)
You can handle file errors:
import json
try:
with open("contacts.json", "r") as file:
contacts = json.load(file)
except FileNotFoundError:
print("No saved contacts found. Starting fresh.")
contacts = {}
import json
def load_contacts():
# TODO: Try to load contacts from "contacts.json"
# TODO: If file doesn't exist, return empty dictionary
# TODO: If file is corrupted, return empty dictionary and show error
pass
def save_contacts(contacts):
# TODO: Save contacts to "contacts.json" in JSON format
# TODO: Show confirmation message
pass
def add_contact(contacts):
# TODO: Get name and details, add to dictionary, print confirmation
pass
def view_all_contacts(contacts):
# TODO: Loop through contacts and print each one, handle empty book
pass
def search_contact(contacts):
# TODO: Search by name, print info if found or error if not
pass
def delete_contact(contacts):
# TODO: Delete by name, print confirmation or error
pass
# Main program
contacts = load_contacts()
while True:
print("\n=== Contact Book Menu ===")
print("1. Add contact")
print("2. View all contacts")
print("3. Search for contact")
print("4. Delete contact")
print("5. Quit")
choice = input("\nChoice: ")
if choice == "1":
add_contact(contacts)
elif choice == "2":
view_all_contacts(contacts)
elif choice == "3":
search_contact(contacts)
elif choice == "4":
delete_contact(contacts)
elif choice == "5":
save_contacts(contacts)
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")