逐行读取文件并使用正则的Python程序末尾抛出AttributeError问题
解决正则匹配时的
NoneType AttributeError问题 嘿,我一眼就看出问题所在啦——你的代码里直接调用了pattern.search(line).group(),但当某一行完全匹配不上你的正则表达式时,search()方法会返回None,这时候你再去调用.group(),可不就会抛出AttributeError嘛!
大概率是你的文件最后有空白行,或者某一行的格式完全不符合(?<=\>)(.*?)(?=\|)这个正则的规则,导致匹配失败返回了None。
给你两个改进方向,一步步解决问题:
1. 先检查匹配结果,再调用group()
最直接的修复就是先判断search()的返回值是不是None,只有当匹配成功时才去提取内容:
import re pattern = re.compile(r'(?<=\>)(.*?)(?=\|)') input_file = open('input.fas', 'r') while True: line = input_file.readline() if not line: # 读取到文件末尾,退出循环 break # 先拿到匹配结果 match_result = pattern.search(line) # 只有匹配成功时才处理 if match_result: output = match_result.group() # 这里写你对output的处理逻辑,比如打印、写入文件等 else: # 可选:打印提示,知道哪一行出了问题 print(f"注意:该行没有匹配到内容 -> {line.strip()}") input_file.close() # 别忘了关闭文件!
2. 用更Pythonic的方式读取文件
其实Python里逐行读文件不用while True,用with语句更安全(自动帮你关闭文件),写法也更简洁:
import re pattern = re.compile(r'(?<=\>)(.*?)(?=\|)') # with语句会自动管理文件上下文,不用手动close with open('input.fas', 'r') as input_file: for line in input_file: line = line.strip() # 去掉行首尾的空白和换行符 if not line: # 跳过空行,避免无效匹配 continue match_result = pattern.search(line) if match_result: output = match_result.group() # 替换成你的业务逻辑,比如print(output)或者写入输出文件 print(output) else: print(f"警告:未匹配到内容的行 -> {line}")
这样改之后,不仅能避免NoneType的错误,还能让代码更健壮,同时也能清楚看到哪一行出了问题,方便你排查文件内容的格式问题。
内容的提问来源于stack exchange,提问作者Blank
相关产品推荐
相关产品推荐

