python 读取数据出现UnicodeDecodeError:: ‘utf-8‘ codec can‘t decode byte 0xc8 in position 0: invalid contin

解决方法:

读取时也可以用二进制模式打开的文件(包括模式参数中的'rb')将内容作为字节对象,而不进行任何解码。

然后使用line.decode(‘utf-8’,errors = 'ignore')解码,其中的errors参数:修改字符集参数,一般这种情况出现得较多是在国标码(GBK)和utf-8之间选择出现了问题。出现异常报错是由于设置了decode()方法的第二个参数errors为严格('strict')形式造成的,因为默认就是这个参数,将其更改为'ignore'等即可。

举例:

import os
path = r'.\es'

for file in os.listdir(path):
    file_path = os.path.join(path,file)
    file_output = os.path.join(path,f"{file}.txt")
    with open(file_path,mode='rb') as f:            # 使用二进制形式'rb'进行读取
        with open(file_output,mode='a+',encoding = 'utf-8') as w:
            for line in f.readlines():
                line_content = line.decode('utf-8',errors='ignore').strip().split()    # 使用'utf-8'进行解码,errors='ignore'进行忽略
                if len(line_content) == 0:
                    w.write('\n')
                else:
                    w.write(str(line_content[0].strip()) + ' ' + str(line_content[-1].strip()) + '\n')


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值