import os
def grep_files(strings, directory='.'):
"""
在指定目录中递归地搜索包含所有字符串的文件。
参数:
strings:包含要搜索的所有字符串的列表
directory:要搜索的目录(默认为'.'当前目录)
返回值:
包含所有字符串的所有文件的列表
"""
matching_files = []
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
path = os.path.join(dirpath, filename)
with open(path, 'r') as f:
contents = f.read()
if all(s in contents for s in strings):
matching_files.append(path)
return matching_files
这个函数使用Python的os模块来递归地遍历指定的目录。对于每个文件,它打开文件并检查文件内容中是否包含所有搜索字符串。如果是,则将文件路径添加到匹配文件列表中。
要使用此函数,只需传入要搜索的字符串列表即可:
strings_to_search = ['apple', 'banana', 'orange']
matching_files = grep_files(strings_to_search)
print(matching_files)
这将在当前目录及其子目录中搜索包含“apple”,“banana”和“orange”的所有文件,并将找到的文件路径打印出来。