无法从文件中加载泡菜对象 [英] Unable to load pickle object from file
本文介绍了无法从文件中加载泡菜对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我只是尝试使用pickle模块并学习其功能和实用程序.我已经写了这小段代码,但这给我带来了麻烦.
I'm just trying out the pickle module and learning its functions and utilities. I've written this small piece of code, but it's giving me trouble.
import pickle
myfile = open("C:\\Users\\The Folder\\databin.txt", 'r+') #databin.txt is completely blank
class A:
def __init__ (self):
self.variable = 25
self.random = 55
pickle.dump (A, myfile, -1) #HIGHEST_PROTOCOL
pickle.load (myfile)
然后我得到以下错误:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
pickle.load (myfile)
File "C:\Python27\lib\pickle.py", line 1378, in load
return Unpickler(file).load()
File "C:\Python27\lib\pickle.py", line 858, in load
dispatch[key](self)
KeyError: '\x00'
推荐答案
您需要先关闭文件,然后重新打开文件才能正常工作;并使用二进制模式打开文件.
You'd need to close the file first, then reopen it for that to work; and use binary mode to open your file.
最后但并非最不重要的是,泡菜只能存储类的实例,而不能存储类本身:
Last but not least, pickle can store instances of classes only, not the classes themselves:
filename = "C:\\Users\\The Folder\\databin.txt"
with open(filename, 'wb') as myfile:
pickle.dump(A(), myfile, -1) #HIGHEST_PROTOCOL
with open(filename, 'rb') as myfile:
pickle.load(myfile)
在这里,我已将该文件用作上下文管理器,当with
套件退出时,它将自动关闭.
Here I've used the file as a context manager, it'll close automatically when the with
suite is exited.
这篇关于无法从文件中加载泡菜对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文