Skip to content

UnicodeDecodeError: 'utf-8' codec 能't decode 字节

错误信息

                'utf-8' codec 能't decode 字节 0x80 in 位置 0
              

快速摘要

你 tried 到 decode 字节 using encoding (如 UTF-8) 那个 doesn't match 实际字节内容.

为什么发生

  • 读取 file 使用错误 encoding (e.g., UTF-8 对比 Latin-1)

  • Decoding binary 数据 as 文本

  • Mixing encodings 当处理文本从 不同源

最小示例

✗ 错误代码
data = b'\x80\x81'
text = data.decode('utf-8')  # UnicodeDecodeError
✓ 修复代码
data = b'\x80\x81'
text = data.decode('utf-8', errors='replace')
print(text)  # Two replacement characters

字节 aren't 有效 UTF-8. Using 错误='replace' substitutes 无效字节使用 Unicode replacement character.

如何诊断

  • 检查 file's 实际 encoding 使用 hex editor or chardet

  • Try 不同 encodings: 'utf-8', 'latin-1', 'cp1252'

  • Use 错误='replace' or 错误='ignore' 到 handle 坏字节

如何修复

  • Specify 正确 encoding 当打开: 打开(f, encoding='latin-1')

  • Use 错误='replace' 到 replace 坏字节使用 placeholder

  • Use 错误='ignore' 到 skip 坏字节

如何预防

  • 总是 specify encoding explicitly 当打开 files

  • Use chardet 到 detect unknown encodings

  • Standardize on UTF-8 for 所有文本 files

相关资源

相关术语

相关课程

← 返回语言