我已经在python3中使用协议3对文件进行了腌制,现在我需要使用python2对其进行腌制,该怎么办? [英] I have pickled files using protocol 3 in python3, and now I need to unpickle them with python2, what can I do?

查看:77
本文介绍了我已经在python3中使用协议3对文件进行了腌制,现在我需要使用python2对其进行腌制,该怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

mydata = pickle.load(myfile, "rb")
ValueError: unsupported pickle protocol: 3

这与以下内容有关: ValueError:不支持的泡菜协议:3,python2泡菜无法加载python 3泡菜转储的文件?

很明显,有远见,如果要使用python2对其进行腌制,则必须将protocol=2设置为在python3中转储您的pickle文件时.

So clearly, with foresight, you must set protocol=2 when you dump your pickle file in python3 if you want to be able to unpickle it with python2.

但是,如果不幸的是您被卡在使用协议3在python 3中腌制的文件怎么办,现在必须使用python2读取它们,该怎么办?有什么解决方法吗?

However what if you unfortunately are stuck with files that were pickled in python 3 using protocol 3 and now you must read them with python2? Is there any workaround?

有一个相关的问题,但这似乎是一个不同的核心问题: unpickle python2中python3中的OrderedDict

There is a related question, but it seems to be a different core issue: unpickle OrderedDict from python3 in python2

推荐答案

如果您无法控制这些腌制文件的创建方式,并且必须在Python 2.7中加载它们,然后很遗憾,没有简单的解决方法.

If you have no control over the way these pickled files were created, and you must load them in Python 2.7, then unfortunately there is no easy workaround.

也许创建文件的人没有意识到Python 3中的pickle的默认协议是"3",但是这是向后不兼容的.

Perhaps the person who created the files wasn’t aware of the fact that the default protocol for pickle in Python 3 is "3", but that this is backward-incompatible.

文档:

当前默认协议为3;为Python 3.0设计的向后不兼容的协议.

Currently the default protocol is 3; a backward-incompatible protocol designed for Python 3.0.

如果它们是一组固定的文件,那么一种变通方法是只编写一个脚本,该脚本以迭代方式在Python 3.0中加载协议3腌制的文件,然后使用protocol=2作为一次修复来重新编写它们.然后,您将能够在Python 2.7中阅读它们.此外,如果将来将要创建代码需要处理的文件,请确保修改了写入这些文件的原始代码.

If they are a fixed set of files then a workaround may be to just write a script that iteratively loads the protocol 3 pickled files in Python 3.0 and then re-writes them using protocol=2 as one-shot fix. Then you will be able to read them in Python 2.7. Also make sure that the original code writing these files is modified if there are future files that are going to be created that your code will need to handle.

@Kay指出此解决方案在实践中有多简单:

@Kay points out how simple this solution is in practice: I have pickled files using protocol 3 in python3, and now I need to unpickle them with python2, what can I do?

就像pickle.dump(pickle.load(sys.stdin),sys.stdout,2)一样容易

As easy as pickle.dump(pickle.load(sys.stdin), sys.stdout, 2)

这篇关于我已经在python3中使用协议3对文件进行了腌制,现在我需要使用python2对其进行腌制,该怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆