使用pandas读取csv时,经常出现UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid continuation byte。
为了避免读取异常,可以在pd.read_csv函数中设置encoding参数值,但是往往治标不治本。
实际上可以使用 chardet 等检测文件的编码,一劳永逸,代码如下:
impoet pandas as pd
import chardet
from pathlib import Path
def csv_reader(csv_path):
detected = chardet.detect(Path(csv_path).read_bytes())
# detected示例 {'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
return pd.read_csv(csv_path, encoding=detected.get("encoding"))