Python Pickle 在读取和未正确读取时产生 EOF 错误
我正在尝试使用以下方法来腌制患者对象:
theFile = open(str(location)+str(filename)+'.pkl','wb')
pickle.dump(self,theFile)
theFile.close()
这效果很好,并且可以根据需要成功写入文件。但!当我尝试从拇指加载数据时,出现 EOF 错误 XOR 它加载拇指中不存在的旧数据。我不知道这些旧数据来自哪里,考虑到 pickle 包含所有正确的保存数据...
加载操作:
theFile = open('/media/SUPER/hr4e/thumb/patient.pkl','r+')
self = pickle.load(theFile)
theFile.close()
一个例子是:我更改所需对象的属性并保存它。该属性显然保存在 pickle 文件中,但是当我在另一台计算机上重新加载 pickle 文件时,它不会读取 pickle 并加载旧数据。我检查了一下它是否正在读取泡菜,它是......
我错过了关于泡菜的任何微妙的细微差别吗?或者,我是否只是使用错误的读写参数来保存和加载泡菜?
I am trying to pickle a patient object by using:
theFile = open(str(location)+str(filename)+'.pkl','wb')
pickle.dump(self,theFile)
theFile.close()
This works well and successfully writes to the file as desired. But! When I try to load the data from the thumb, I get an EOF error XOR it loads old data that is not present in the thumb. I don't know where this old data is coming from, considering the pickle contains all the correct saved data...
Loading operation:
theFile = open('/media/SUPER/hr4e/thumb/patient.pkl','r+')
self = pickle.load(theFile)
theFile.close()
An example would be: I change an attribute of the desired object and save it. The attribute is clearly saved in the pickle file, but when I reload the pickle file on another computer, it doesn't read the pickle and loads old data. I checked to see if it was reading the pickle and it is...
Are there any subtle nuances about pickles that I am missing? Or, am I just using the wrong read and write arguments for the pickle saving and loading?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在方法内分配给 self 只会更新变量
self
在该方法中指向的内容;它不会更新对象本身。要加载它,请从类方法或函数返回新加载的对象。尝试这样的代码:Assigning to self inside a method only updates what the variable
self
points to in that method; it doesn't update the object itself. To load it, instead return a newly loaded object from a classmethod or function. Try code like this:以二进制模式打开文件。例如
theFile = open('/media/SUPER/hr4e/thumb/patent.pkl','r+b')
Open the file in binary mode. e.g.
theFile = open('/media/SUPER/hr4e/thumb/patient.pkl','r+b')
我最终腌制了对象的属性字典。这样效果好多了。例子:
I ended up pickling the object's attributes dictionary. That worked much better. Example: