python-2.7 - 在python2中,加载pickle文件( 来自 python3 )

我有一个pickle文件


>>> with open("wikilinks.pickle","rb") as f:
... titles, links = pickle.load(f)
... 
>>> len(titles)
13421

我可以在python3中加载它,但是,当我尝试在python2中加载它时,出现以下消息:


 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中加载?

时间:

Python 3默认使用的默认pickling协议与Python 2使用的默认协议不兼容。但是,如果您可以修改产生wikilink.pickle的代码,则可以告诉它使用更早的协议之一(0,1,或2),Python 2会理解得很好。

但请注意,Python 3字符串将在Python 2中作为Unicode字符串出现,这在某些用例中可能会产生令人惊讶的结果。


$ 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'x80x02]qx00(Kx01Kx02Xx03x00x00x00abcqx01e.'
>>> 
$ 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('x80x02]qx00(Kx01Kx02Xx03x00x00x00abcqx01e.')
[1, 2, u'abc']

...