Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python文本搜索不同文件夹中的.txt文件,并打印文件名和文件夹名_Python_File_Path_Directory_Python Os - Fatal编程技术网

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

Python文本搜索不同文件夹中的.txt文件,并打印文件名和文件夹名,python,file,path,directory,python-os,Python,File,Path,Directory,Python Os,我正在用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(dir

我正在用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)

但是我想为脚本做一个扩展:不仅可以在一个文件夹(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))

将它们放在同一目录中,然后执行
os.walk()
方法
walk()
仅通过自顶向下或自底向上遍历目录树来生成目录树中的文件名。此脚本似乎只显示包含每个文件夹信息的前一个文件,而不是所有文件夹的信息them@HalfPintBoy是否只有第一个文件符合条件?例如,当我用相同的搜索词将所有文件放在一个文件夹中时,它会给我10个匹配项,当我在两个不同的文件夹(相同的文件)中进行检查时,结果是每个文件夹中只有一个匹配项。