如何用Python的glob.glob获取同级指定目录下的路径?
Python glob.glob 匹配指定目录下所有路径的等效写法
Python 的 glob.glob 本身不支持 Bash 那种 {A,B}/* 的大括号扩展语法,但有几种实用方式能实现你要的效果:
直接拼接结果:这是最直观的方式,和你当前分开调用的逻辑一致,只是合并成一个列表:
import glob target_paths = glob.glob('A/*') + glob.glob('B/*')批量处理多目录:如果要匹配的目录数量较多,用
itertools.chain可以高效合并结果,避免多次列表拼接的开销:import glob from itertools import chain target_dirs = ['A', 'B', 'OtherTargetDir'] target_paths = list(chain.from_iterable(glob.glob(f'{dir}/*') for dir in target_dirs))避坑提醒:不要直接尝试
glob.glob('{A,B}/*'),Python 的 glob 会把大括号当作路径的字面量去匹配,只会查找名为{A,B}的目录下的内容,完全不符合需求。
如果你的 Python 版本在 3.4 及以上,也可以用 pathlib 模块实现,写法更简洁:
from pathlib import Path # 循环拼接 target_paths = [] for dir_name in ['A', 'B']: target_paths.extend(Path('.').glob(f'{dir_name}/*')) # 或者用列表推导式简化 target_paths = [p for dir_name in ['A', 'B'] for p in Path('.').glob(f'{dir_name}/*')]
内容的提问来源于stack exchange,提问作者ilibarra
相关产品推荐
相关产品推荐

