python编码问题 utf-8 codec can not decode byte

问题描述

在用python读txt文件的时候遇到了编码问题:‘utf-8’ codec can’t decode byte 0xb70,同样的代码之前在python2的时候是不会出现问题的。用百度找了一下也没能找到有效的解决方法,后来在stackoverflow上找到了类似的问题。
stackoverflow问题

解决方案

str = unicode(str, errors='replace')

or

str = unicode(str, errors='ignore')

这个操作会删除(忽略)有问题的字符,并返回不包含这些字符的字符串。

可选方案

使用codecs模块中的open方法读取文件:

import codecs
with codecs.open(file_name, 'r', encoding='utf-8',
                 errors='ignore') as fdata:

与python2中相似的方法

有人提到,要使python3处理文件与和python2尽可能相似,可以使用:

with open(filename, encoding="latin-1") as datafile:
    # work on datafile here
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章