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