试图从我的联系人python代码传递姓名和号码列表,但只保存最后的输入



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("NamettContact Number")
# for key in contact:
#    print("{}tt{}".format(key,contact.get(key)))
while True:
choice = int(input(" 1. Add new contact n 2. Search contact n 3. Display contactn 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

我已经尝试过,但只能保存最后的输入,而不是所有的联系人列表。有什么办法救他们吗。我一直在尝试不同的代码,因为我已经评论了一些尝试不同的方式,但它只打印最后的输入。我希望它保存一个输出文件与第一次保存保存所有的联系,然后,如果他们添加或更新一个联系人,将其保存为更新保存的文件,如选择7。但是我只能保存最后一个输入。我还在学习python的工作原理,这是我无法理解的。

您正在寻找序列化,这(通常)最好留给库。json库可以轻松地处理读取和写入字典到文件。

要编写字典,请看json.dump():

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

最新更新