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="")