基本上,马丁所说的是正确的。您需要先关闭文件,然后再重新打开它。如果你不这样做,你会得到一个错误。我使用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'>