如何在windows上的python中在其他目录的文件中搜索模式?
我正在写一个程序,在这个程序中,我需要在另一个目录的文件中找到一个特定的单词。 例如:我在如何在windows上的python中在其他目录的文件中搜索模式?,python,python-3.x,Python,Python 3.x,我正在写一个程序,在这个程序中,我需要在另一个目录的文件中找到一个特定的单词。 例如:我在C:\python\directory中,我想搜索位于D驱动器中的文件中的模式D:\Sample\u file\file.txt。 我在sample_file目录中有许多这样的文件,我需要在其中 在该文件中查找特定单词。 例如:在D:\Sample\u file\file.txt中,我需要找到“hello world”和 在D:\Sample\u file\file1.txt中,我需要找到“0个未找到的文件
C:\python\directory
中,我想搜索位于D驱动器中的文件中的模式<代码>D:\Sample\u file\file.txt。
我在sample_file目录中有许多这样的文件,我需要在其中
在该文件中查找特定单词。
例如:在D:\Sample\u file\file.txt
中,我需要找到“hello world”
和
在D:\Sample\u file\file1.txt中,我需要找到“0个未找到的文件”,然后在
D:\Sample\u other\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
循环的示例。文件
应该是文件的完整路径列表
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%确定这是最好的方法,但我希望它能帮助您。这里是您正在寻找的for
循环的示例。文件
应该是文件的完整路径列表
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%确定这是最好的方法,但我希望它能帮助你