查找包含给定文件(Python)字符串的文件夹中的所有文件

时间:2017-11-19 00:44:21

标签: python

我有一个包含大量文件的文件夹,其中一些包含一个或多个关键字,我还有一个单独的文件,仅包含关键字,每行一个字,如下所示:

keyword1
keyword2
keyword3

我需要找到所有这些文件。

所以我有这个代码

import os

directory = os.listdir("D:/where_2_search")

with open('what_2search.txt','r') as searchlist:
    for line in searchlist:
    print(line)
    for fname in directory:
        if os.path.isfile("D:/where_2_search" + os.sep + fname):
            searchedfile = open("D:/where_2_search" + os.sep + fname, 'r')
            if line in searchedfile.read():
                print('found string in file %s' % fname)
            else:
                print('string not found')
            searchedfile.close()

但它不起作用,因为我只收到负面结果。我怎么能解决它?

2 个答案:

答案 0 :(得分:1)

我认为最好使用的模块是enter image description here。您只需从文件中读取关键字并获取与关键字匹配的文件列表。

注意未经测试。我建议你自己做。这只是一个帮助/概述。

{{1}}

答案 1 :(得分:0)

您的关键字末尾有换行符

尝试更改为

if line.rstrip() in searchedfile.read():