我正在尝试使用以下方法来 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
