Unable to load pickle object from file

社会主义新天地 提交于 2019-12-13 10:24:56

问题


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)

I then get the following error:

 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'

回答1:


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)

Here I've used the file as a context manager, it'll close automatically when the with suite is exited.




回答2:


Basically, what Martin says is correct. You need to close the file first, then reopen it. If you don't you get an error. I'm using dill, instead of pickle, so I can pickle the class.

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

Now, close the file, and try again… remember to open it again first.

>>> 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'>


来源:https://stackoverflow.com/questions/11920792/unable-to-load-pickle-object-from-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!