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