我正在尝试修改此语法,以在用户选择选项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 contacts\n3.Search for and edit a contact\n4.Exit\n")
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 contact\n2.Print out contacts\n3.Search for and edit a contact\n4.Exit\n"))
答案 0 :(得分:0)
您可以做类似的事情
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 contacts\n3.Search for and edit a contact\n4.Exit\n")
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