Python 文本搜索不同文件夹中的.txt 文件并打印文件和文件夹的名称

Python Text Searching in .txt files in different folders with printing the name of file and folder

我正在 Python 中制作一个脚本,用于在选定文件夹中的一堆 .txt 文件中搜索选定术语(word/couple 单词、句子),并打印出名称包含所选术语的 .txt 文件。目前使用 os 模块工作得很好:

import os

dirname = '/Users/User/Documents/test/reports'

search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]

for f in os.listdir(dirname):
    with open(os.path.join(dirname,f), "r", encoding="latin-1") as infile:
        text =  infile.read()

    if all(term in text for term in search_terms):
        print (f)

但我想对脚本进行扩展:不仅可以在一个文件夹 (dirname) 中搜索,而且可以在两个文件夹中搜索 (dirname1, dirname2),这两个文件夹也包含 .txt 文件。此外,我不仅想打印搜索到的报告的名称,还想打印它所在的目录 (dirname) 的名称。是否可以使用 os 模块来做到这一点,或者会有其他一些方法来做到这一点?

您可以像这样遍历目录名:

import os

dirnames = ['/Users/User/Documents/test/reports','/Users/User/Documents/test/reports2']

search_terms = ['Pressure']
search_terms = [x.lower() for x in search_terms]
for dir_name in dirnames:
    for f in os.listdir(dir_name):
        with open(os.path.join(dir_name, f), "r", encoding="latin-1") as infile:
            text = infile.read()

        if all(term in text for term in search_terms):
            print("{} in {} directory".format(f, dir_name))