2012-08-12 150 views
-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' 
+0

你的代碼沒有意義,你可以只醃對象的實例,但不能直接調用類。 – 2012-08-12 08:47:48

回答

3

你需要首先關閉該文件,然後重新打開該工作;並使用二進制模式打開您的文件。

最後但並非最不重要的,泡菜可以存儲實例類只,而不是類本身:

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套房已退出。

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