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

PythonPython 3.xPython 2.7PickleValueerror

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAleeeeView Question on Stackoverflow
Solution 1 - PythonMatthiasView Answer on Stackoverflow
Solution 2 - Pythonenrico.bacisView Answer on Stackoverflow