避免读取.csv 文件,格式报错的统一方法

问题:

大家在使用pd.read_csv()读取csv 文件时,是否遇到过

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 11: invalid continuation byte

原因:

这是由于我们的csv 文件格式不确定导致的,有的时候是gbk 格式,有的时候是utf-8格式,

解决方式:

因此为避免在读取时,报错,或者乱码,我们可以在读取文件之前,先对文件格式进行检测,然后将检测的格式带入到pd.read_csv(file,encoding = '检测的格式')

完整代码:

import chardet

def read_csv_with_encodings(file_path):
    with open(file_path, 'rb') as f:
        result = chardet.detect(f.read())
        encoding = result['encoding']
        print(f"文件编码: {encoding}")
    
    df = pd.read_csv(file_path , encoding=encoding)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值