如何为递归目录扫描函数添加glob文件名过滤并存储结果到列表?
实现带文件名模式过滤的递归文件扫描
方案1:改造原os.scandir递归函数,添加过滤逻辑
基于你原有的递归扫描函数,我们可以通过fnmatch模块实现glob风格的文件名匹配,直接在原逻辑中加入过滤判断即可:
import os import fnmatch def scan_recursive(path, pattern): with os.scandir(path) as it: for entry in it: if entry.is_file(): # 匹配文件名是否符合指定模式 if fnmatch.fnmatch(entry.name, pattern): # 用entry.path直接获取系统兼容的完整路径,避免手动拼接的分隔符问题 yield entry.path else: # 递归遍历子目录,传递过滤模式 yield from scan_recursive(entry.path, pattern) # 方式1:手动遍历存入列表 x = [] for file_path in scan_recursive('C:/test/1', '2018-*-photo.jpg'): x.append(file_path) # 方式2:直接将生成器转为列表(更简洁) x = list(scan_recursive('C:/test/1', '2018-*-photo.jpg'))
方案2:直接用pathlib的glob(更简洁高效)
你尝试的Path.glob已经可以实现递归匹配,只需将生成器结果转为列表即可,不需要自己写递归逻辑:
from pathlib import Path def scan_recursive(directory, pattern): # **/ 表示递归遍历所有子目录,glob返回生成器,直接转为列表返回 return list(Path(directory).glob(f'**/{pattern}')) # 使用示例,获取匹配文件的字符串路径 x = [str(file) for file in scan_recursive('C:/test/1', '2018-*-photo.jpg')]
如果需要支持多模式匹配,可修改函数接收模式列表:
from pathlib import Path def scan_recursive(directory, patterns): matched_files = [] for pattern in patterns: matched_files.extend(Path(directory).glob(f'**/{pattern}')) # 转为字符串路径返回 return [str(file) for file in matched_files] # 多模式使用示例 x = scan_recursive('C:/test/1', ['2018-*-photo.jpg', '*.png'])
内容的提问来源于stack exchange,提问作者Леонид
相关产品推荐
相关产品推荐

