我正在编写一个程序,需要在另一个目录的文件中找到特定的单词。例如:我在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
这里是您要查找的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%肯定这是最好的方法,但希望对您有帮助。