“UnicodeDecodeError:'charmap'编解码器无法解码”pickle load

时间:2016-12-21 08:47:40

标签: 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)

当我运行代码时,它会在 pickle.load(f)行返回一个异常,说明:

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 25: character maps to <undefined>

我的机器规格:

  

Python 3.5.2 | Anaconda 4.2.0(64位)| (默认,2016年7月5日,   11:41:13)[MSC v.1900 64 bit(AMD64)]在win32上

1 个答案:

答案 0 :(得分:11)

在Python 3中,pickle模块期望底层文件对象接受或返回 bytes 。您以二进制模式正确打开文件进行写入,但未能在读取时执行相同操作。阅读部分应为:

with open('tweets.dat', 'rb') as f:
   all_tweets = pickle.load(f)

参考:摘自pickle.load(fd)的文档:

  

...因此,文件可以是为二进制读取打开的磁盘文件,io.BytesIO对象或满足此接口的任何其他自定义对象。

相关问题