【发布时间】:2021-07-24 09:20:39
【问题描述】:
我正在继续我之前编写的程序,并试图将输入的数据保存在一个单独的文件中,所以当我重新打开程序时,我会保留数据。
addressbook = []
class Parent:
def Create(self):
create_contact = input('''Please input the details of the contact you would like to create.
''')
addressbook.append(create_contact)
print("Successfully added")
return
def Remove_contact(self):
remove_contact = input('''Please input the details of the contact you would like to remove.
''')
if remove_contact in addressbook:
print(addressbook.remove(remove_contact))
print("Successfully removed contact.")
else:
print("Error", search_contact, "not found in the list")
return
def Search(self):
search_contact = input('''Please input the details of the contact you would like to search for.
''')
if search_contact in addressbook:
print(search_contact, "found in Address Book")
else:
print("Error", search_contact, "not found in the list")
return
def Display_contacts(self):
print("Displaying contacts....", addressbook)
return
def menu(parent):
menu = input('''Address book to store friends contact
-------------------------------------------------------------
-------------------------------------------------------------
Select an option...
1 - Add/Update contact...
2 - Display all contacts...
3 - Search...
4 - Delete contact...
5 - Quit
''')
if menu == '1':
parent.Create()
elif menu == '2':
parent.Display_contacts()
elif menu == '3':
parent.Search()
elif menu == '4':
parent.Remove_contact()
elif menu == '5':
print("Quitting program")
quit()
else:
print("I did not understand that... Please try again")
p = Parent()
menu(p)
这是我的旧代码,我正在考虑导入一个包含列表的文件,然后添加到该列表中。这是一个合适的方法还是有更简单的方法?谢谢!
【问题讨论】:
-
在
quit()之前添加要写入文本文件的代码 -
您可能会发现 atexit 模块对此docs.python.org/3/library/atexit.html很有用