Python-将联系人保存到通讯簿并打印通讯簿



当用户选择选项1时,我试图修改此语法以将输入联系人保存到save.txt文件中,当用户选择选择选项2时,我将打印save.txt的内容。请帮忙?非常感谢。

这是Addressbook.py:

from contact import Contact
addressBook = []
choice = 0
save = open("save.txt", 'r')
s = save.read()
s = s.split("~")
while len(s)-4 >= 0:
addressBook.append(Contact(s.pop(0), s.pop(0), s.pop(0), s.pop(0)))
print("Hello I am an addressbook! What do you want to do?n1.Add contact")
print("2.Print out contactsn3.Search for and edit a contactn4.Exitn")
choice = int(input())
while choice != 4:
if choice == 1:
addressBook.append(Contact(input("First name?"), input("Last name?"), input("Phone number?"), input("Email?")))
elif choice == 2:
for x in range(len(addressBook)):
print(addressBook[x].ToString())
elif choice == 3:
print("????")
choice = int(input("What do you want to do?n1.Add contactn2.Print out contactsn3.Search for and edit a contactn4.Exitn"))

你可以做一些类似的事情

class Contact:
def __init__(self, first_name, last_name, phone_num, email):
self.first_name = first_name
self.last_name = last_name
self.phone_num = phone_num
self.email = email
def __str__(self):
return "~".join([self.first_name, self.last_name, self.phone_num, self.email])
address_book = []
try:
with open("save.txt") as save_file:
for contact in save_file:
address_book.append(Contact(*contact.rstrip().split("~")))
except FileNotFoundError as fefe:
pass
print("Hello I am an addressbook! What do you want to do?n1.Add contact")
print("2.Print out contactsn3.Search for and edit a contactn4.Exitn")
while True:
choice = int(input("Choice: "))
if choice == 1:
address_book.append(Contact(input("First name?"), input("Last name?"), input("Phone number?"), input("Email?")))
elif choice == 2:
print(*[contact for contact in address_book], sep="n")
elif choice == 3:
pass
elif choice == 4:
with open("save.txt", "w") as save_file:
for contact in address_book:
save_file.write(str(contact) + "n")
break

最新更新