无法从文件加载pickle对象

时间:2012-08-12 08:24:04

标签: python pickle

我只是尝试了pickle模块并学习它的功能和实用程序。我写了这小段代码,但它给了我麻烦。

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'

2 个答案:

答案 0 :(得分:3)

您需要先关闭该文件,然后重新打开该文件才能正常工作;并使用二进制模式打开您的文件。

最后但并非最不重要的是,pickle只能存储类的实例,而不是类本身:

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套件时自动关闭。

答案 1 :(得分:0)

基本上,马丁说的是正确的。您需要先关闭文件,然后重新打开它。 如果你没有收到错误。我使用dill而不是泡菜,所以我可以挑选这个课程。

Python 3.3.5 (default, Mar 10 2014, 21:37:38) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> myfile = open('pickle.pkl', 'rb+')
>>> 
>>> class A:
...   def __init__(self):
...     self.variable = 25
...     self.random = 55
... 
>>> dill.dump(A, myfile, 2)
>>> dill.load(myfile)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mmckerns/lib/python3.3/site-packages/dill-0.2.2.dev-py3.3.egg/dill/dill.py", line 187, in load
    obj = pik.load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/pickle.py", line 847, in load
    raise EOFError
EOFError

现在,关闭文件,然后再试一次......记得先打开它。

>>> myfile.close()
>>> dill.load(myfile)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/mmckerns/lib/python3.3/site-packages/dill-0.2.2.dev-py3.3.egg/dill/dill.py", line 187, in load
    obj = pik.load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/pickle.py", line 845, in load
    key = read(1)
ValueError: read of closed file
>>> 
>>> myfile = open('pickle.pkl', 'rb+')
>>> dill.load(myfile)
<class '__main__.A'>