Create a contact book application to store, view, and manage contacts.
import csv
def add_contact(contacts):
name = input("Enter name: ")
phone = input("Enter phone number: ")
contacts.append({'name': name, 'phone': phone})
def view_contacts(contacts):
print("Contacts:")
for contact in contacts:
print(f"Name: {contact['name']}, Phone: {contact['phone']}")
def load_contacts(filename):
try:
with open(filename, mode='r') as file:
reader = csv.DictReader(file)
return list(reader)
except FileNotFoundError:
return []
def save_contacts(filename, contacts):
with open(filename, mode='w', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['name', 'phone'])
writer.writeheader()
writer.writerows(contacts)
def main():
contacts = load_contacts('contacts.csv')
while True:
print("\n1. Add Contact\n2. View Contacts\n3. Save and Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_contact(contacts)
elif choice == '2':
view_contacts(contacts)
elif choice == '3':
save_contacts('contacts.csv', contacts)
break
else:
print("Invalid choice!")
if __name__ == "__main__":
main()