解決Python打開文件報錯UnicodeDecodeError: 'gbk' codec can't decode byte

用Python打開文件時報錯:

UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0x80 in position 10: illegal multibyte sequence

打開文件的代碼如下:

f = open('music.text')  # 打開music.text文件
file_data = f.read()  # 讀取文件內容
print(file_data)  # 打印文件內容

解決方法:
編碼問題導致。使用打開函數open()的時候,需要使用正確的編碼格式,修改如下:

f = open('music.text', encoding='utf-8')  # 打開music.text文件
file_data = f.read()  # 讀取文件內容
print(file_data)  # 打印文件內容

修改後,運行不再報錯:
print——file

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