如何在Windows上的python中的其他目录的文件中搜索模式?

问题描述 投票:0回答:1

我正在编写一个程序,需要在另一个目录的文件中找到特定的单词。例如:我在C:\python\ directory中,我想在D驱动器中的文件中搜索模式。 D:\Sample_file\file.txt。我在sample_file目录中有很多这样的文件,我需要在其中在该文件中找到特定的单词。例如:在D:\Sample_file\file.txt中,我需要找到"hello world",然后在D:\Sample_file\file1.txt中,我需要找到“找不到0个文件”,然后在D:\Sample_another\file3.txt我需要找到“天哪!”我该怎么做。

我尝试过os.relpath,但无法达到预期的结果

import os
paths = 'D:/'

def dir_list_folder(paths):
    for folderName in os.listdir(paths):     
       if (folderName.find('.') == -1):
           folderPath = os.path.join(paths,folderName );
           dir_list_folder(folderPath);
       else:
           print ('Files is :'+ folderName );

我希望如果它与模式匹配,它应该返回true,否则返回false

python python-3.x
1个回答
0
投票

这里是您要查找的for循环的示例。预期files是文件的完整路径的列表。

patterns = ['hello world', '0 files found']


for fileName in files:
    with open(fileName) as f:
        allLines = {x.strip() for x in f.readlines()}
    for pattern in patterns:
        if pattern in allLines:
            print('`%s` detected in %s' % (pattern, fileName))
            # then you can return True
        # and here False

[不是100%肯定这是最好的方法,但希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.