UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0xad in position 2: illegal multibyte sequence报错解决

新建一个txt文本,输入内容为:中国是一个伟大的国家。
打开文本文件读取里面的内容:

textFile=open("my.txt","rt") #t表示文本文件方式
print(textFile.readline())
textFile.close()

报错如下:
在这里插入图片描述
原因是encoding参数默认为None,默认读取英文字符,而文本中为中文字符,故需修改encoding=‘utf-8’,从而读取文本中的中文字符。

修改后代码如下:

textFile=open("my.txt","rt",encoding='utf-8') #t表示文本文件方式
print(textFile.readline())
textFile.close()

输出:

中国是个伟大的国家!

猜你喜欢

转载自blog.csdn.net/qq_40445009/article/details/118815731