我正在使用 python pickle 来维护联系人列表。我有两个问题:
- 添加新人后,我看不到打印所有人员的整个列表。只打印新人。代码有什么问题?
- 如果我要删除一个联系人,如何更改本地文件?
编码:
import pickle
class contact:
person= {};
def add(self, name,contact):
self.person[name] = contact;
store2file(self.person);
#print(self.contactlist);
def delete(self,name):
del self.person[name];
#print(self.person);
def modify(self,name,contact):
self.person[name] = contact;
store2file(self.person);
def store2file(person):
mycontactfile = 'contactlist.data';
f = open(mycontactfile,'wb');
pickle.dump(person,f);
f.close();
f = open(mycontactfile,'rb');
storedcontact = pickle.load(f);
print (storedcontact);
def main():
mycontact = contact();
option = input('Pls select option: 1 Add; 2 delete; 3 update: ');
if option == '1':
name = input('Enter the name: ');
contactNo = input('Enter the contact number: ');
mycontact.add(name,contactNo);
store2file(mycontact);
elif option =='2':
name = input('Enter the name: ');
mycontact.delete(name);
elif option =='3':
name = input('Enter the name: ');
contactNo = input('Enter the contact number: ');
mycontact.modify(name,contactNo);
else:
print('Pls select proper option');
main()