Python讀取文件內容時報錯:UnicodeDecodeError: 'gbk' codec can't decode byte...

Python代碼如下:

#!/usr/bin/python3

print("讀取的文件內容:")
with open("myfile.txt", mode='r') as f:
    for line in f:
        print(line, end="")

運行代碼,異常信息如下:

Traceback (most recent call last):
  File "E:/git@github/python/python3/except/file.py", line 5, in <module>
    for line in f:
UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 28: illegal multibyte sequence

 

由於文件內容有中文,解決方法是在open方法指定參數encoding='UTF-8':

#!/usr/bin/python3

print("讀取的文件內容:")
with open("myfile.txt", mode='r', encoding='UTF-8') as f:
    for line in f:
        print(line, end="")

 

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