python的pickle模块实现了基本的数据序列和反序列化。通
python2使用的是cPickle模块,而在python3中cPickle已经被取消,取而代之的是pickle模块。
开发过程中,我曾经遇到一个奇怪的问题,在读取一个文件时候,使用python2的如下方式:
python3读取python2存储的pkl文件时,如下:
import pickle
dicts = pickle.load(open("./a.pkl"))
报错:
TypeError: ‘str’ does not support the buffer interface
改用用二进制方式打开文件:
import pickle
dicts = pickle.load(open("./a.pkl", "rb"))
报错:
UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xe8 in position 0: ordinal not in range(128)
我们需要告诉pickle:how to convert Python bytestring data to Python 3 strings,The default is to try and decode all string data as ASCII,所以代码改为:
import pickle
dicts = pickle.load(open("./a.pkl", "rb"), encoding='iso-8859-1')
成功。