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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章