python读取文件出错UnicodeDecodeError: ‘gbk‘ codec can‘t decode

file = open(r"D:\test.txt","r")
txt = file.read()
print(txt)
file.close()

运行代码报错:

Traceback (most recent call last):
  File "D:/python_study/hello.py", line 29, in
    txt = file.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xaa in position 16: illegal multibyte sequence

上面报错的意思就是,默认以gbk的方式读取数据,但是文本数据是utf-8类型的,这是需要用到另一个参数encoding,也就是把它编码成与文本一样类型的格式,下面的代码encoding="utf-8"就是要修改的地方,如果不写编码格式,默认是encoding="gbk"的

#open("文件路径","操作模式","编码格式")

把上面第一行代码改为:

file = open(r"D:\test.txt","r",encoding="utf_8")

你可能感兴趣的:(python,python)