1. 程式人生 > >解決Python讀取檔案時出現UnicodeDecodeError: 'gbk' codec can't decode byte * in position * illegal multibyte

解決Python讀取檔案時出現UnicodeDecodeError: 'gbk' codec can't decode byte * in position * illegal multibyte

解決Python讀取檔案時出現UnicodeDecodeError: 'gbk' codec can't decode byte...

用Python在讀取某個html檔案時會遇到下面問題:

出問題的程式碼:

1 if __name__ == '__main__':
2     fileHandler = open('../report.html', mode='r')
3 
4     report_lines = fileHandler.readlines()
5 for line in report_lines: 6 print(line.rstrip())

修改方式是在open方法指定引數encoding='UTF-8':

if __name__ == '__main__':
    fileHandler = open('../report.html', mode='r', encoding='UTF-8')

    report_lines = fileHandler.readlines()
    for line in report_lines:
        print(line.rstrip())