Python Pickle 在读取时出现 EOF 错误且未正确读取

2 投票
3 回答
2447 浏览
提问于 2025-04-17 04:12

我正在尝试用以下代码把一个病人对象保存到文件里:

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

这个方法运行得很好,成功地把数据写入了文件。但是!当我尝试从这个文件里加载数据时,我遇到了一个EOF错误,或者它加载的是一些旧的数据,而这些数据在文件里并不存在。我搞不清楚这些旧数据是从哪里来的,因为我确认这个文件里保存了所有正确的数据...

加载操作的代码是:

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

举个例子:我修改了想要的对象的一个属性并保存了它。这个属性在文件里确实被保存了,但当我在另一台电脑上重新加载这个文件时,它却没有读取到最新的数据,而是加载了旧的数据。我检查过,确实是读取了这个文件...

我是不是遗漏了关于文件保存的某些细节?还是说我在保存和加载文件时使用了错误的参数?

3 个回答

0

我最后选择把对象的属性字典进行了序列化,这样效果好多了。举个例子:

self.__dict__ = pickle.load(file('data/pickles/clinic.pkl','r+b'))
0

以二进制模式打开文件。比如说:
theFile = open('/media/SUPER/hr4e/thumb/patient.pkl','r+b')

1

在一个方法里给自己(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

撰写回答