Python3 读取txt文件报错
2019-09-09
35
0
使用Python在按文本读取文件时,有时会出现如下错误
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb9 in position 1026: illegal multibyte sequence
Python3的原代码如下:
def GetFileContent(f):
file = open(f, 'rt'")
s = file.read()
return s
网上有人说fopen的打开方式换成rb方式,这样是没有问题,但有时我们就是需要字符串,而非字节流。
怎么办呢?
一般因为文件比较大,我们无法细细的查找,就算按指定的字符集转存,也会出现类似一样的问题呢?
这怎么办呢,很简单,对于在文本解码过程中我们忽略错误即可。
def GetFileContent(f):
file = open(f, 'rt',errors="ignore")
s = file.read()
return s