Python3教程
+ -

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

0 篇笔记 写笔记

Python3 读取txt文件报错
使用Python在按文本读取文件时,有时会出现如下错误UnicodeDecodeError: 'gbk' codec can't decode byte 0xb9 in position 1026: illegal multibyte sequencePython3的原代码如......
取消
感谢您的支持,我会继续努力的!
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

您的支持,是我们前进的动力!