import os
import fnmatch
def find_files(directory, keyword):
""" 在给定目录及其子目录中查找包含关键词的文件 """
for root, dirs, files in os.walk(directory):
for basename in files:
if keyword in basename:
# 使用 os.path.join 来确保路径分隔符正确
filename = os.path.join(root, basename)
yield filename
# 使用方法
if __name__ == "__main__":
# 指定要搜索的目录
directory_to_search = '/path/to/directory' # 注意这里的路径分隔符取决于操作系统
# 指定要搜索的关键词
keyword_to_search = 'keyword'
# 查找并打印结果
for filepath in find_files(directory_to_search, keyword_to_search):
print(filepath)
标签:__,files,search,keyword,python,查找文件,关键字,directory,os
From: https://www.cnblogs.com/longronglang/p/18409485