python学习笔记:python版本和pickle序列化问题

pickle 可用于python序列化和反序列化
现在有5种不同的协议进行序列化

Protocol version 0 is the original “human-readable” protocol and is backwards compatible with earlier versions of Python.

Protocol version 1 is an old binary format which is also compatible with earlier versions of Python.

Protocol version 2 was introduced in Python 2.3. It provides much more efficient pickling of new-style classes. Refer to PEP 307 for information about improvements brought by protocol 2.

Protocol version 3 was added in Python 3.0. It has explicit support for bytes objects and cannot be unpickled by Python 2.x. This is the default protocol, and the recommended protocol when compatibility with other Python 3 versions is required.

Protocol version 4 was added in Python 3.4. It adds support for very large objects, pickling more kinds of objects, and some data format optimizations. Refer to PEP 3154 for information about improvements brought by protocol 4.

当我们在使用pickle.dump进行序列化的时候,如果不指定Protocol ,python2会默认使用2,python3会默认使用3
这样当使用一个版本进行序列化的时候,在想使用另一个版本进行加载就会出现错误,例如我使用python2来反序列化python3产生的文件,出现了这样的错误

ValueError: unsupported pickle protocol: 3

解决方法(使用python3反序列化 在设置python2可使用的Protocol参数进行序列化)

import pickle
testpkl = pickle.loads(open("./test.pkl", "rb").read())
pickle.dump(testpkl, open("testpkl_py2.pkl","wb"), protocol=2)

参考:
https://blog.csdn.net/zziahgf/article/details/80253125
https://docs.python.org/3/library/pickle.html#pickle.dump

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值