如果在 for 循环中找不到与 re.findall 的匹配项,如何打印?
How to print if no matches are found with re.findall in a for loop?
我的第一个post!我目前正在尝试编写一个脚本,该脚本遍历充满 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)
我的第一个post!我目前正在尝试编写一个脚本,该脚本遍历充满 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)