Python报错-UnicodeDecodeError: 'gbk' codec can't decode byte 0x81 in position 35: incomplete multibyte sequence

问题描述:读文件报错

 

 

【代码】:

with open("D:\Code\Python\data.txt") as file_object:
    contents = file_object.read()
print(contents)

【报错提示】:

Traceback (most recent call last):
  File "d:\Code\Python\open.py", line 2, in <module>
    contents = file_object.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0x81 in position 35: incomplete multibyte sequence

 

【解决方法】:
把python中打开文件方式设置为UTF-8.

【代码】:

with open("D:\Code\Python\data.txt",encoding='UTF-8') as file_object:
    contents = file_object.read()
print(contents)

【运行结果】:

123456789
987654321
hello world!

 

posted @ 2022-10-25 10:58  Mr_宋先生  阅读(1426)  评论(0编辑  收藏  举报