python encoding_error ai_generated true

UnicodeDecodeError: 'utf-8' 编解码器无法解码位置 0 的字节 0xff:无效起始字节

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

ID: python/pandas-csv-unicode-decode

其他格式: JSON · Markdown 中文 · English
80%修复率
90%置信度
0证据数
2024-02-19首次发现

版本兼容性

版本状态引入弃用备注
3.x active — — —

根因分析

pd.read_csv 默认使用 UTF-8,但文件编码为 UTF-16(BOM 0xFF 0xFE)、Latin-1 或 CP1252。位置 0 的 0xff 是 UTF-16 LE BOM。

English

pd.read_csv defaults to UTF-8, but the file is encoded in UTF-16 (BOM 0xFF 0xFE), Latin-1, or CP1252. 0xff at position 0 is the UTF-16 LE BOM.

generic

解决方案

  1. 95% 成功率
    pd.read_csv(path, encoding='utf-16')  # or 'latin-1' / 'cp1252'
  2. 90% 成功率
    Detect with `import chardet; enc = chardet.detect(open(path,'rb').read(10000))['encoding']`

无效尝试

常见但无效的做法:

  1. 85% 失败

    Silently corrupts non-ASCII text

  2. 90% 失败

    Same decode error on open()