python文件的提取问题

img


有没有同学帮忙解释一下这个是什么意思,该怎么改正呢?我才开学python,谢谢大家的帮忙!!

gbk编码无法解析字符0x8c,请换成utf8编码。
比如

file = open(path,"r",encoding="utf_8")

也可以将代码贴出来看看。
如果有用,望采纳,谢谢!

详细解答如下,望采纳


Python 默认使用 utf-8 编码解析文件内容,所以如果你的文件使用了 gbk 编码,那么在读取文件时需要指定使用 gbk 编码来解析文件内容。你可以这样做:

with open("myfile.txt", "r", encoding="gbk") as f:
    for line in f:
        print(line)

如果你发现你的文件中有无法解析的字符,例如 0x8c,那么你可以使用 Python 的 errors 参数来指定如何处理这些错误,例如:

with open("myfile.txt", "r", encoding="gbk", errors="ignore") as f:
    for line in f:
        print(line)

这样,Python 将会忽略那些无法解析的字符,并继续读取文件内容。

我举一个列子,希望对你用帮助

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