我希望能够将多个对象添加到pickle文件中,以后能够检索它。我到了可以保存对象的地步,但是当我加载文件时,只加载了最后一个条目。我的错是什么?
import pickle
class People():
def __init__(self, name, surname, age, mobile_no, home_no):
self.name = name
self.surname = surname
self.age = age
self.mobile_no = mobile_no
self.home_no = home_no
def DisplayContacts(self):
print("First Name: \t", self.name)
print("Surname: \t", self.surname)
print("Age: \t", self.age)
print("Mobile Number: \t", self.mobile_no)
print("Home Number: \t", self.home_no)
print()
def addContact():
newname = str(input("First name: \t"))
newsurname = str(input("Surname: \t"))
newage = int(input("Age: \t"))
newmobile_no = int(input("Mobile Number: \t"))
newhome_no = int(input("Home Number: \t"))
newContact = People(newname, newsurname, newage, newmobile_no, newhome_no)
return newContact
cont = 1
contacts = []
while cont == 1:
user = input("Do you want to add contact? (Y/N)")
if user == "Y" or user == "y":
print ("works")
contacts.append(addContact())
file = open("List.pickle", "wb")
pickle.dump(contacts, file, pickle.HIGHEST_PROTOCOL)
file.close()
else:
print ("111")
cont = 0
useropen = input("open file? (Y/N)")
if useropen == "Y" or useropen == "y":
with open ("List.pickle", "rb") as pickled_file:
contacts = pickle.load(pickled_file)
else:
print("Null")
现在,当我尝试加载文件时,它似乎是空的:
import pickle
class People():
def __init__(self, name, surname, age, mobile_no, home_no):
self.name = name
self.surname = surname
self.age = age
self.mobile_no = mobile_no
self.home_no = home_no
def DisplayContacts(self):
print("First Name: \t", self.name)
print("Surname: \t", self.surname)
print("Age: \t", self.age)
print("Mobile Number: \t", self.mobile_no)
print("Home Number: \t", self.home_no)
print()
def addContact():
newname = str(input("First name: \t"))
newsurname = str(input("Surname: \t"))
newage = int(input("Age: \t"))
newmobile_no = int(input("Mobile Number: \t"))
newhome_no = int(input("Home Number: \t"))
newContact = People(newname, newsurname, newage, newmobile_no, newhome_no)
return newContact
cont = 1
contacts = []
while cont == 1:
user = input("Do you want to add contact? (Y/N)")
if user == "Y" or user == "y":
print ("works")
contacts.append(addContact())
file = open("CList.pickle", "ab")
pickle.dump(contacts, file, pickle.HIGHEST_PROTOCOL)
file.close()
else:
print ("111")
cont = 0
useropen = input("open file? (Y/N)")
if useropen == "Y" or useropen == "y":
with open ("CList.pickle", "rb") as pickled_file:
contacts = pickle.load(pickled_file)
else:
print("Null")
答案 0 :(得分:4)
您正在while
循环的每次迭代中截断您的Pickle文件,因为您是以"wb"
模式打开它。
由于您在循环期间不断向contacts
列表添加联系人(然后在每次迭代时将一个单独的副本转储到另一个联系人 - 可能不是您想要的那个),我只需要整个pickle转储部分代码并在while
循环之后移动它,转储完整的联系人列表一次 - 不需要多个对象。
答案 1 :(得分:4)
您正在使用模式wb
打开您的pickle文件,该文件会截断(在写入任何新内容之前将文件设置为空)。您想要的模式是a
,可以打开以进行追加。
答案 2 :(得分:2)
添加到@Ethan Furman所说的内容,Windows和unix(reference)中'b'
的功能似乎有所不同。您的代码可能在unix上运行良好,但会在windows os上截断