【问题标题】:Find all files in folder containing strings from given file (Python)查找包含给定文件中字符串的文件夹中的所有文件(Python)
【发布时间】:2017-11-19 09:37:37
【问题描述】:

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

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()

但它不起作用,因为我只收到负面结果。我该如何解决?

【问题讨论】:

  • 这可能只是在示例中,但请注意缩进

标签: python


【解决方案1】:

我认为最好使用的模块是glob。您可以简单地从文件中读取关键字并获取与关键字匹配的文件列表。

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

from glob import glob
import os

with open('what_2search.txt','r') as searchlist:
    keywords= searchlist

found_files = []
# You might want to change the working directory as follow if needed
os.chdir(path_where_those_files_are)
for keyword in keywords:
    found_files.append(glob(keyword)) # Here is a little bug. But can easily sort this out

print(found_files) # List of files needed

【讨论】:

    【解决方案2】:

    关键字末尾有换行符

    试着改成这个

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

    【讨论】:

    • 不会改变任何事情,抱歉。
    • 奇怪。我已经验证它可以解决我系统上的问题。
    猜你喜欢
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多