为什么Python 3 Pickle无法读取Python 2 Pickle数据?
我有一个Python 2泡菜文件,当我尝试使用Python 3读取它时,它显示以下错误:
UnicodeDecodeError:'ascii'编解码器无法解码BYTE 0xc3位置0:不在范围(128)< /code>
以下是Python 2和Python 3中的一些代码样本:
python_2_dump.py
# -*- coding: utf-8 -*-
# Python 2 version
import cPickle
test = {
'Á': 'A',
'á': 'a',
'Ã': 'A',
'ã': 'a',
'Â': 'A',
'â': 'a',
}
with open('test.pickle', 'w') as f:
cPickle.dump(test, f)
python_3_3_load.py
# Python 3 version
import pickle
with open('test.pickle', 'rb') as f:
print(pickle.load(f))
是否有任何原因Python 3未检测到旧协议并转换转换相应吗?如果相反,即Python 2阅读Python 3腌制数据,那是有道理的。
I have a Python 2 pickle file that when I try to read it with Python 3 it shows the following error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Here are some code sample in Python 2 and Python 3:
python_2_dump.py
# -*- coding: utf-8 -*-
# Python 2 version
import cPickle
test = {
'Á': 'A',
'á': 'a',
'Ã': 'A',
'ã': 'a',
'Â': 'A',
'â': 'a',
}
with open('test.pickle', 'w') as f:
cPickle.dump(test, f)
python_3_load.py
# Python 3 version
import pickle
with open('test.pickle', 'rb') as f:
print(pickle.load(f))
Is there any reason Python 3 doesn't detect the old protocol and convert it accordingly? If it was the other way around, i.e. Python 2 reading a Python 3 pickle data, it makes sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如
但是,您需要使用
fix_imports
,编码
和errors
来控制Python 2生成的Pickle流的兼容性支持。 https://docs.python.org/3.10/library/pickle.html#pickle.unpickler“ rel =“ nofollow noreferrer”>相关文档:在您的示例中,它将读取
test.pickle
,如果您通过encoding ='utf-8'
:<代码> print(pickle.load(f,encoding ='utf-8'))
输出:
The protocol is detected automatically, as stated in the docs:
However, you need to use
fix_imports
,encoding
anderrors
to control compatibility support for pickle stream generated by Python 2. The relevant docs:In your example, it will read the
test.pickle
if you passencoding='utf-8'
:print(pickle.load(f, encoding='utf-8'))
output: