【python】python读取文件报错UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence

2023-07-31,,

python读取文件报错UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence

示例代码:

fileName = 'E:/2/采集数据_pswf12_180大0小35750_20181206.txt'

currentFile = open(fileName)
content = currentFile.read()
print(content)

报错原因:

要打开的文件中,有‘gbk’解析不了的文本内容

那么可能是文件格式并非'gbk'格式的。

解决方法:

1.先设定编码方式打开文件

currentFile = open(fileName,encoding='gbk')

当然,如果上面报错就是'gbk'编码打开文件失败,那你这里还是指定gbk打开文件,是极大可能报错的。

2.切换其他的文件编码方式

currentFile = open(fileName,encoding='utf-8')

一般情况下,切换后是可以解决问题的。

3.如果第二步依旧没有解决,可以选择使用errors='ignore'属性忽略编译不了的问题[如果只是想打开文件的话]

currentFile = open(fileName,encoding='gbk',errors='ignore')

但是这样虽然可以打开文件,极大可能出现读取乱码的问题

最终,推荐第二种!!!

===========如果,想在打开文件之前,就能判断出文件文本的编码方式,然后根据对应的编码方式打开文件,岂不是更好?点进去===========

【python】python读取文件报错UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence的相关教程结束。

《【python】python读取文件报错UnicodeDecodeError: 'gbk' codec can't decode byte 0xac in position 2: illegal multibyte sequence.doc》

下载本文的Word格式文档,以方便收藏与打印。