NASAAndr3w07
NASAAndr3w07

Reputation: 23

Trying to pass in the list of name and number from my contact python code but only save the very last input


import re
contact = {}

def display_contact():
    for name, number in sorted((k,v) for k, v in contact.items()):
        print(f'Name: {name}, Number: {number}')



#def display_contact():
# print("Name\t\tContact Number")
# for key in contact:
#    print("{}\t\t{}".format(key,contact.get(key)))

while True:
  choice = int(input(" 1. Add new contact \n 2. Search contact \n 3. Display contact\n 4. Edit contact \n 5. Delete contact \n 6. Save your contact as a file \n 7. Update Saved List \n 8. Exit \n Your choice: "))
  
  if choice == 1:
    while True:
      name = input("Enter the contact name ")
      if re.fullmatch(r'[a-zA-Z]+', name):
        break
       
    while True:
      try:
        phone = int(input("Enter number "))
      except ValueError:
        print("Sorry you can only enter a phone number")
        continue
      else:
        break
    contact[name] = phone
    
  elif choice == 2:
    search_name = input("Enter contact name ")
    if search_name in contact:
      print(search_name, "'s contact number is ", contact[search_name])
    else: 
      print("Name is not found in contact book")
      
  elif choice == 3:
    if not contact:
      print("Empty Phonebook")
    else: 
      display_contact()
      
  elif choice == 4:
    edit_contact = input("Enter the contact to be edited ")
    if edit_contact in contact:
      phone = input("Enter number")
      contact[edit_contact]=phone
      print("Contact Updated")
      display_contact()
    else:
      print("Name is not found in contact book")
      
  elif choice == 5:
    del_contact = input("Enter the contact to be deleted ")
    if del_contact in contact:
      confirm = input("Do you want to delete this contact Yes or No? ")
      if confirm == 'Yes' or confirm == 'yes':
        contact.pop(del_contact)
      display_contact
    else:
      print("Name is not found in phone book")



  elif choice == 6:
    confirm = input("Do you want to save your contact-book Yes or No?")
 
    if confirm == 'Yes' or confirm == 'yes':
      with open('contact_list.txt','w') as file:
            file.write(str(contact))
      print("Your contact-book is saved!")            
    else:
      print("Your contact book was not saved.")
 # else:
    
  elif choice == 7:
    confirm = input("Do you want to update your saved contact-book Yes or No?")
 
    if confirm == 'Yes' or confirm == 'yes':
      f = open("Saved_Contact_List.txt" , "a")
      f.write("Name = " + str(name))
      
      f.write(" Number = " + str(phone))
      f.close()
      




      
      #with open('contact_list.txt','a') as file:
      #      file.write(str(contact))
      print("Your contact-book has been updated!")            
    else:
      print("Your contact book was not updated.")  
      
  else:
      break


I have tried but only get to save the last input and not all of the contact list. Any ideas on how to save them all. I have been trying different code as I have comment some out to try a different way but it only print the last input. I would like it to save a output file with the first save to save all the contact then if they add or update a contact to save it as a updated saved file like choice 7. But I only get it to save the last input. I still learning how python works and this is over my head.

Upvotes: 0

Views: 137

Answers (1)

Dash
Dash

Reputation: 1299

You're looking for serialization, which is (usually) best left to libraries. The json library easily handles reading and writing dictionaries to a file.

To write a dictionary, take a look at json.dump():

with open("Saved_Contact_List.txt", "w") as f:
    json.dump(contact, f)

Upvotes: 1

Related Questions