常见报错排查:ModuleNotFoundError 与编码问题

Python 新手最常撞的六类报错,每个都给定位方法和根本原因。

2026-11-15 · 约 6 分钟读完

报错不可怕,可怕的是不知道从哪看。这篇按出现频率排序,讲六类最常见的。

一、ModuleNotFoundError

ModuleNotFoundError: No module named 'requests'

三种可能,按顺序排查:

# 1. 真的没装
pip install requests

# 2. 装到了别的 Python
python -c "import sys; print(sys.executable)"
pip -V          # 看路径是否一致

# 3. 虚拟环境没激活
which python    # Linux
where python    # Windows

第 2 种最常见。判断方法:python -m pip install requests 一定装到当前解释器里,比直接 pip install 可靠。

二、UnicodeDecodeError

UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 1234

读文件时没指定编码,Windows 默认用 GBK,遇到 UTF-8 内容就炸。

# 错
open("data.txt").read()

# 对
open("data.txt", encoding="utf-8").read()

# 更稳:忽略无法解码的字节
open("data.txt", encoding="utf-8", errors="ignore").read()

养成习惯:所有 open() 都写 encoding="utf-8"。 这一条能消掉一半编码问题。

写文件同理:

open("out.csv", "w", encoding="utf-8-sig", newline="")   # 给 Excel 看
open("out.json", "w", encoding="utf-8")                   # 给程序看

三、UnicodeEncodeError(打印中文报错)

UnicodeEncodeError: 'gbk' codec can't encode character '\u2705'

在 Windows 终端打印 emoji 或特殊符号时出现。

import sys
sys.stdout.reconfigure(encoding="utf-8")

或者干脆避免在输出里用 emoji。

四、KeyError / IndexError

KeyError: 'name'
IndexError: list index out of range

都是「取不存在的东西」。

# KeyError:用 get 给默认值
value = data.get("name", "")

# IndexError:先判断长度
if len(items) > 0:
    first = items[0]

# 或者用切片,超界也不报错
first = items[:1]

字典嵌套很深时,get 会写得很长:

# 繁琐
v = d.get("a", {}).get("b", {}).get("c")

# 清晰
from functools import reduce
v = reduce(lambda x, k: (x or {}).get(k), ["a", "b", "c"], d)

五、AttributeError: 'NoneType' object has no attribute

AttributeError: 'NoneType' object has no attribute 'get_text'

链式调用里某一环返回了 None。

# 错
title = soup.select_one("h1").get_text()

# 对
el = soup.select_one("h1")
title = el.get_text(strip=True) if el else ""

凡是可能找不到的元素,都要先判断再取值。 这是爬虫脚本崩掉的头号原因。

六、文件被占用 / 权限不足

PermissionError: [Errno 13] Permission denied: 'data.xlsx'
场景原因解法
文件在 Excel 里开着被独占锁关掉再跑
写到 C:\Program Files需要管理员换目录或以管理员运行
删除只读文件属性问题os.chmod(path, 0o777)
文件被别的进程打开句柄未释放用 lsof 查,或重试

一个通用的重试装饰器:

import time
from functools import wraps

def retry(times=3, delay=1):
    def deco(fn):
        @wraps(fn)
        def wrapper(*a, **kw):
            for i in range(times):
                try:
                    return fn(*a, **kw)
                except (PermissionError, OSError) as e:
                    if i == times - 1:
                        raise
                    time.sleep(delay)
        return wrapper
    return deco

@retry(times=3, delay=2)
def save_file(path, data):
    with open(path, "w", encoding="utf-8") as f:
        f.write(data)

读报错的正确顺序

很多人一看到报错就慌,其实 Python 的 traceback 信息很全。从下往上看:

Traceback (most recent call last):
  File "main.py", line 10, in <module>      ← 最外层调用
    process()
  File "main.py", line 6, in process        ← 实际出错的位置
    data["items"].append(x)
KeyError: 'items'                            ← 错误类型和原因

三个信息点:

  1. 最后一行:错误类型 + 直接原因
  2. 倒数第二段 File 行:出错的具体文件和行号
  3. 中间几行:调用链,能看出是谁触发的

先看最后一行,再定位到那个行号,90% 的问题当场能想明白。

一个自查清单

报错关键词先查什么
ModuleNotFoundError解释器路径、虚拟环境
UnicodeDecodeErroropen() 有没有写 encoding
KeyError用 .get()
IndexError判断长度
NoneType先判断再调用
PermissionError文件是否被占用
SyntaxError看箭头指向的那一行,以及上一行是否漏了冒号/括号