我已经编写了一个小样本代码来试用pickle模块。在pickle.load()语句中面对UnicodeDecodeError。编写编码=' utf-8'也没有效果。 这是代码
import pickle
class NewOne:
def __init__(self):
self.name = "None"
self.age = 0
def entries(self):
self.name = input("Name: ")
self.age = input("Age: ")
obj1 = NewOne()
for i in range(3):
obj1.entries()
pickle.dump(obj1, open("Details", "ab"))
for j in range(3):
obj = pickle.load(open("Details",))
if obj.age == 18:
print("Name: "+obj.name)
答案 0 :(得分:0)
您的代码的主要问题是,每次运行脚本时都要附加到同一文件的末尾,但稍后会加载前三个对象。
实际上,情况比这更糟糕;你应加载前三个对象,但事实上你每次只加载第一个,因为你在pickle.load()
的每次迭代中重新打开文件
可能是文件开头有错误,而且您每次只是因为正在加载文件中的第一个对象而触及此错误。您可以尝试删除Details
文件,看看是否仍然收到错误。
以下代码每次都会创建一个新的details
文件,向其写入三个对象,然后重新加载这三个对象。
import pickle
class NewOne:
def __init__(self):
self.name = "None"
self.age = 0
def entries(self):
self.name = raw_input("Name: ")
self.age = raw_input("Age: ")
obj1 = NewOne()
# Open file for writing. The `with` context manager will automatically close
# it at the end of the loop
with open("Details", "wb") as myfile:
for i in range(3):
obj1.entries()
pickle.dump(obj1, myfile)
# Re-open the file for reading
with open("Details",) as myfile:
for j in range(3):
obj = pickle.load(myfile)
if obj.age == '18':
print("Name: "+obj.name)