我正在用Python编写一个脚本,用于在所选文件夹中的一堆.txt文件中搜索所选术语(单词/偶词、句子(,并打印出包含所选术语的.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)
但我想为脚本做一个扩展:不仅可以在一个文件夹(目录名(中搜索,还可以在两个文件夹中搜索,例如(目录名1,目录名2(,它们也由.txt文件组成。此外,我不仅想打印搜索报告的名称,还想打印它所在的目录(目录名(的名称。是否有可能使用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))