ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

柔情痞子 提交于 2019-11-27 09:42:56

问题


I use pickle to dump a file on python 3, and I use pickle to load the file on python 2, the ValueError appears.

So, python 2 pickle can not load the file dumped by python 3 pickle?

If I want it? How to do?


回答1:


You should write the pickled data with a lower protocol number in Python 3. Python 3 introduced a new protocol with the number 3 (and uses it as default), so switch back to a value of 2 which can be read by Python 2.

Check the protocolparameter in pickle.dump. Your resulting code will look like this.

pickle.dump(your_object, your_file, protocol=2)

There is no protocolparameter in pickle.load because pickle can determine the protocol from the file.




回答2:


Pickle uses different protocols to convert your data to a binary stream.

  • In python 2 there are 3 different protocols (0, 1, 2) and the default is 0.

  • In python 3 there are 5 different protocols (0, 1, 2, 3, 4) and the default is 3.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.



来源:https://stackoverflow.com/questions/25843698/valueerror-unsupported-pickle-protocol-3-python2-pickle-can-not-load-the-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!