ValueError: 不支持 pickle 协议: 3,python2 pickle 无法加载被 python3 pickle 转储的文件?

我使用 pickle 转储 python3上的文件,并使用 pickle 加载 python2上的文件,ValueError 出现。

那么,python2 pickle 不能加载被 python3 pickle 转储的文件吗?

如果我想要? 怎么办?

144442 次浏览

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.

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.