问题描述
我有一个泡菜文件,带有
I have a pickle file, with
>>> with open("wikilinks.pickle", "rb") as f:
... titles, links = pickle.load(f)
...
>>> len(titles)
13421
我可以在python3中加载它.但是,当我尝试在python2中加载它时,出现以下消息:追溯(最近一次通话):
I can load it in python3.However, when I try to load it in python2, I get this message:Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/usr/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/usr/lib/python2.7/pickle.py", line 886, in load_proto
raise ValueError, "unsupported pickle protocol: %d" % proto
ValueError: unsupported pickle protocol: 3
那么如何在python2中加载它呢?
So how to load it in python2?
推荐答案
默认酸洗协议与Python 2中使用的协议不兼容.但是,如果您可以修改生成wikilink.pickle
的代码,则可以告诉它使用更早的协议之一( 0、1或2),Python 2会很好理解的.
The default pickling protocol used by default in Python 3 is incompatible with the protocol used by Python 2. However, if you can modify the code that produces wikilink.pickle
, you can tell it to use one of the earlier protocols (0, 1, or 2) which Python 2 will understand just fine.
但是请注意,Python 3字符串将在Python 2中作为Unicode字符串出现,这在某些用例中可能会令人惊讶.
Be warned, though, that Python 3 strings will come up as Unicode strings in Python 2, which may be surprising in some use cases.
$ python3
Python 3.4.1 (default, May 19 2014, 17:23:49)
[GCC 4.9.0 20140507 (prerelease)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> pickle.dumps([1, 2, 'abc'], 2)
b'\x80\x02]q\x00(K\x01K\x02X\x03\x00\x00\x00abcq\x01e.'
>>>
$ python
Python 2.7.8 (default, Jul 1 2014, 17:30:21)
[GCC 4.9.0 20140604 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import cPickle
>>> cPickle.loads('\x80\x02]q\x00(K\x01K\x02X\x03\x00\x00\x00abcq\x01e.')
[1, 2, u'abc']
这篇关于在python2中加载pickle文件(来自python3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!