首页 > 解决方案 > glob() 中的多个数组

问题描述

我有以下代码可以正常工作,但在使用文件夹通配符作为其解析的文件夹时速度很慢。我需要将此限制为我想提供的列表以限制其搜索;

如何将此文件夹列表(例如 folder=['A,B,C'] )解析为 glob,以便将其搜索限制在这些文件夹中,而不是使用 * 通配符。由于文件夹数量众多,这将使其工作得更快。

tra=['70XX','81YY']
TargetFolder = r'C:\ELK\LOGS\ATH\DEST'
all_files = []
for directory in tra:
    files = glob.glob('Z:/{}/*/asts_data_logger/*.bz2'.format(directory))
    for f in files:
        current_path = Path(f)
        if current_path.name in filenames_i_want:
            print(f"found target file: {f}")
            shutil.copy2(f, TargetFolder)

标签: pythonglob

解决方案


遍历您的文件夹列表并将它们替换为路径名,就像您对tra.

import itertools

folders=['A', 'B', 'C']
tra=['70XX','81YY']
TargetFolder = r'C:\ELK\LOGS\ATH\DEST'
all_files = []
for directory, folder in itertools.product(tra, folders):
    files = glob.glob('Z:/{}/{}/asts_data_logger/*.bz2'.format(directory, folder))
    for f in files:
        current_path = Path(f)
        if current_path.name in filenames_i_want:
            print(f"found target file: {f}")
            shutil.copy2(f, TargetFolder)

推荐阅读