解决 Python 报错 UnicodeDecodeError: 'utf-8' codec can't decode byte 的排查指南
排查与解决 Python 读取文本或文件时提示 UnicodeDecodeError: 'utf-8' codec can't decode byte 编码异常的完整方案。
问题现象
在 Python 脚本中使用 open() 读取外部文件或处理网络字节流时,抛出致命异常:
Traceback (most recent call last):
File "read_data.py", line 8, in <module>
content = f.read()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb7 in position 4: invalid start byte
触发根因
- 目标文件实际是以 GBK / GB2312 / GB18030(Windows 简体中文常用编码)或 Latin-1 / CP1252 保存的,但在读取时默认或显式指定了
utf-8编码。 - 尝试将真正的二进制文件(如图片、压缩包、编译输出)以文本模式(
'r')打开并按 UTF-8 解码。 - 文本中混入了零星损坏的非标准非法字节。
解决步骤与操作命令
步骤一:检测文件的实际编码格式
在 Linux / macOS 终端使用 file 命令或 Python charset_normalizer 检测:
file -i data.txt
# 例如输出:data.txt: text/plain; charset=iso-8859-1
在 Python 中自动探测:
import charset_normalizer
with open("data.txt", "rb") as f:
result = charset_normalizer.from_bytes(f.read()).best()
encoding = result.encoding
print("Detected encoding:", encoding)
步骤二:显式指定正确的编码格式打开文件
对于中文 Windows 生成的 CSV 或文本文件,通常为 gbk 或 gb18030:
with open("data.txt", "r", encoding="gb18030") as f:
content = f.read()
步骤三:使用 errors='ignore' 或 'replace' 容错处理
若文件中仅包含极少数不可解析的脏字符,使用容错策略避免程序崩溃:
# 忽略非法字节
with open("data.txt", "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
# 或将非法字节替换为问号占位符
with open("data.txt", "r", encoding="utf-8", errors="replace") as f:
content = f.read()
验证确认
重新运行解析脚本: 文件顺畅完成全文加载与字段提取,中文内容正常还原,未抛出任何 UnicodeDecodeError。


