Cod*_*ork 4 python encoding utf-8 pickle
我想在文件中保存一组Tweet对象.Tweet类实例包含utf8编码字符.你可以看到下面的代码:
class Tweet:
author='';
text='';
time='';
date='';
timestamp='';
with open('tweets.dat','wb') as f:
pickle.dump(all_tweets,f)
with open('tweets.dat') as f:
all_tweets = pickle.load(f)
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,它会在pickle.load(f)行上返回一个异常,说明:
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 25: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
我的机器规格:
Python 3.5.2 | Anaconda 4.2.0(64位)| (默认情况下,2016年7月5日,11:41:13)[winv上的MSC v.1900 64位(AMD64)]
Ser*_*sta 17
在Python 3中,pickle模块期望底层文件对象接受或返回字节.您以二进制模式正确打开文件进行写入,但未能在读取时执行相同操作.阅读部分应为:
with open('tweets.dat', 'rb') as f:
all_tweets = pickle.load(f)
Run Code Online (Sandbox Code Playgroud)
参考:摘自以下文件pickle.load(fd):
...因此,文件可以是为二进制读取打开的磁盘文件,io.BytesIO对象或满足此接口的任何其他自定义对象.