pickle 在python 2和python 3中兼容性问题
转载自http://blog.csdn.net/lanchunhui/article/details/50034921
以下的演示均在Python 3环境下进行。
我们以一个简单的文件打开和文件读为例说明,pickle读文件时可能存在的编码问题:
1 import pickle 2 3 # 使用with结构避免手动的文件关闭操作 4 with open('xxx.pkl', 'rb') as objFile: 5 self= pickle.load(objFile)
如果沿用python 2.x的做法,如上所示,而不做任何编码格式上的设置,直接运行,编译器会提示如下错误:
1 UnicodeDecodeError: 'ascii' codec can't decode byte 0x99 in position 2: ordinal not in range(128)
0. 一种 import 的兼容性解决思路
1 try: 2 import cPickle as pickle 3 except ImportError: 4 import pickle
1. 解决方案
一种可行的解决方案是:
1 with open('xxx.pkl', 'rb') as objFile: 2 u = pickle._Unpickler(objFile) 3 u.encoding = 'latin1' 4 self = u.load()
或者更为精炼地:
1 with open('xxx.pkl', 'rb') as objFile: 2 training_data, validation_data, test_data = pickle.load(f, encoding='latin1')
references
[1] <Pickle incompatability of numpy arrays between Python 2 and 3>