python pandas读取各种编码方式的csv文件

python读取csv文件时经常由于编码方式出现文件读取失败的情况,于是写了一个简单的函数。

通过chardet库的detect函数确定csv文件的编码方式,再使用pd.read_csv读取文件。

import pandas as pd
import chardet

def readdf(csv_file_path):
    f=open(csv_file_path, 'rb')
    d = chardet.detect(f.read())['encoding']
    f.close()  
    df = pd.read_csv(csv_file_path,encoding=d)	
    return df

你可能感兴趣的:(pandas,python,开发语言)