gpt4 book ai didi

Python Pickle 在读取时产生 EOF 错误并且读取不正确

转载 作者:太空宇宙 更新时间:2023-11-04 06:26:22 25 4
gpt4 key购买 nike

我正在尝试使用以下方法来 pickle 患者对象:

theFile = open(str(location)+str(filename)+'.pkl','wb')
pickle.dump(self,theFile)
theFile.close()

这很好用,并成功地写入了所需的文件。但!当我尝试从 thumb 加载数据时,出现 EOF 错误 XOR,它加载了 thumb 中不存在的旧数据。我不知道这些旧数据是从哪里来的,考虑到 pickle 包含所有正确保存的数据......

加载操作:

theFile = open('/media/SUPER/hr4e/thumb/patient.pkl','r+')
self = pickle.load(theFile)
theFile.close()

例如:我更改了所需对象的属性并保存了它。该属性显然保存在 pickle 文件中,但是当我在另一台计算机上重新加载 pickle 文件时,它不会读取 pickle 并加载旧数据。我检查它是否正在读取 pickle ,它是......

我是否遗漏了 pickle 的任何细微差别?或者,我是否只是使用了错误的读写参数来保存和加载 pickle ?

最佳答案

在方法中给 self 赋值只会更新变量 self 在该方法中指向的内容;它不会更新对象本身。要加载它,而不是从类方法或函数返回一个新加载的对象。试试这样的代码:

import pickle
class Patient(object):
def __init__(self, name):
self.name = name

def save(self, location, filename):
theFile = open(str(location)+str(filename)+'.pkl','wb')
pickle.dump(self,theFile)
theFile.close()

@classmethod
def load(cls, location, filename):
theFile = open(str(location)+str(filename)+'.pkl','rb')
m = pickle.load(theFile)
theFile.close()
return m

p = Patient("Bob")
print p.name

# save the patient
p.save("c:\\temp\\", "bob")

# load the patient - this could be in a new session
l = Patient.load("c:\\temp\\", "bob")
print l.name

关于Python Pickle 在读取时产生 EOF 错误并且读取不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7748056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com