You need to enable JavaScript to run this app. Python正则扫描目录txt文件时,NoneType对象触发AttributeError报错问题
优惠活动
大模型
产品
解决方案
定价
更多

Python正则扫描目录txt文件时,NoneType对象触发AttributeError报错问题

报错根因

re.search()的返回规则非常明确:

  • 匹配成功时,返回带.group()方法的Match对象
  • 匹配失败时,直接返回None,不存在任何实例方法

你当前的代码存在三处逻辑错位:

  • 循环遍历拿到的文件名变量file,被直接覆盖为search()的返回值,变量语义混乱
  • 没有先判断返回值类型就直接调用.group():当返回值为None时,因None本身没有.group()属性,直接触发AttributeError
  • 原判断逻辑if file.group() is None从设计上就无法生效:只要search()没匹配到结果,代码在执行.group()这一步就会崩溃,根本走不到if判断;如果能顺利执行.group(),说明已经处于匹配成功的状态,这个分支永远不会命中。
修正实现

调整判断顺序,直接通过search()的返回值是否为None判定匹配结果,同时修复原代码反复打开文件、不释放文件句柄的问题,修正后核心可运行代码如下:

import os
import re

# 接收用户输入的正则规则和目标目录
match_rule = input("Set what variable to analyze for.\n")
target_dir = input("Set what folder to analyze.\n")

os.chdir(target_dir)
regex_obj = re.compile(match_rule)

for file_name in os.listdir(target_dir):
    # 仅处理后缀为.txt的文件
    if not file_name.endswith('.txt'):
        continue
    # 用上下文管理器打开文件,自动关闭文件句柄,避免资源占用
    with open(file_name, 'r', encoding='utf-8') as fp:
        file_content = fp.read()
    # 直接判断匹配结果,无需提前调用.group()
    match_result = regex_obj.search(file_content)
    if match_result is None:
        print(f"{file_name} negative.")
    else:
        print(f"{file_name} positive.")

调整完成后,程序扫描到无匹配内容的txt文件时,会正常进入None判断分支输出negative标记,不会再触发属性报错。

内容的提问来源于stack exchange,提问作者bigphatty42

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.16 13:36:07