如果在 for 循环中使用 re.findall 找不到匹配项,如何打印?

问题描述

我的第一篇文章!我目前正在尝试编写一个脚本,该脚本遍历一个充满 HTML 文件的目录并使用 re.findall 进行解析。到目前为止,它正确地打印出匹配的文件,尽管它看起来也正在打印 else 语句(我认为它不会除非 if 语句失败?):

import re
import os
import codecs

dirpath = #path to local directory

for file_a in os.listdir(dirpath):
    filepath = os.path.join(dirpath,file_a)
    f = codecs.open(filepath,'r','utf8')
    lines = f.readlines()
    for line in lines:
        if re.findall('Pattern X',line):
            print('Pattern X detected!',file_a)
        else:
            print('Pattern X not detected!',file_a)

我得到一个类似的输出

Pattern X detected! test.html
Pattern X not detected! test.html

提前致谢!

解决方法

如果您只想知道该字符串是否存在于文件中,那么您不需要 findall

import re
import os
import codecs

dirpath = #path to local directory

for file_a in os.listdir(dirpath):
    filepath = os.path.join(dirpath,file_a)
    f = codecs.open(filepath,'r','utf8')
    if re.search('Pattern X',f.read()):
        print('Pattern X detected!',file_a)
    else:
        print('Pattern X not detected!',file_a)