-1

我只是在尝试 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'
4

2 回答 2

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

于 2012-08-12T08:28:17.620 回答
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'>
于 2014-10-13T14:42:56.467 回答