在Python中搜索包含多个关键字的文件名,可以使用os
模块来遍历目录并检查文件名是否包含指定的关键字。以下是一个示例代码:
import os
def search_files_with_keywords(directory, keywords):
"""
搜索指定目录下包含多个关键字的文件名
:param directory: 要搜索的目录路径
:param keywords: 包含的关键字列表
:return: 包含关键字的文件名列表
"""
result = []
for root, dirs, files in os.walk(directory):
for file in files:
if all(keyword in file for keyword in keywords):
result.append(os.path.join(root, file))
return result
# 示例用法
directory = '/path/to/search'
keywords = ['keyword1', 'keyword2']
files_with_keywords = search_files_with_keywords(directory, keywords)
print(files_with_keywords)
(root, dirs, files)
,其中 root
是当前目录路径,dirs
是当前目录下的子目录列表,files
是当前目录下的文件列表。True
。def search_files_with_keywords_case_insensitive(directory, keywords):
result = []
for root, dirs, files in os.walk(directory):
for file in files:
if all(keyword.lower() in file.lower() for keyword in keywords):
result.append(os.path.join(root, file))
return result
import concurrent.futures
def search_files_with_keywords_parallel(directory, keywords):
result = []
def check_file(file):
return all(keyword in file for keyword in keywords)
with concurrent.futures.ThreadPoolExecutor() as executor:
futures = []
for root, dirs, files in os.walk(directory):
for file in files:
futures.append(executor.submit(check_file, file))
if all(future.result() for future in futures):
result.append(os.path.join(root, file))
return result
通过以上方法,你可以高效地在Python中搜索包含多个关键字的文件名,并解决可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云