One - One Code All

Blog Content

python3使用pickle读取文件提示TypeError或者UnicodeDecodeError的解决办法

Python   2011-09-16 17:23:05

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')

成功。


上一篇:BeautifulSoup路径选择css选择器
下一篇:python网页获取urllib和requests获取到的content-length长度不一致

The minute you think of giving up, think of the reason why you held on so long.