Python:使用Glob查找特定的子文件夹

时间:2017-03-15 03:29:26

标签: python glob directory

我希望以递归方式搜索包含许多子文件夹的文件夹。某些子文件夹包含我想要循环的特定文件夹。

我熟悉glob.glob方法来查找特定文件:

import glob, os
from os import listdir
from os.path import isfile, join

os.chdir(pathname) #change directory to path of choice
files = [f for f in glob.glob("filename.filetype") if isfile(join(idir, f))]

目录中的某些子文件夹具有时间戳(YYYYMMDD),因为它们的名称都包含相同的文件名。其中一些子文件夹包含名称中的文件夹,我们称之为“A”。我希望创建一个代码,以递归方式搜索这些“特定子文件夹”中名为“A”的文件夹。有没有办法使用glob.glob在目录中查找这些特定的子文件夹?

我知道一个类似的问题: How can I search sub-folders using glob.glob module in Python?

但是这个人似乎在寻找特定的文件,而我正在寻找路径名。

1 个答案:

答案 0 :(得分:1)

您可以使用将在树上行走的os.walk。每次迭代都会显示目录及其直接子目录,因此测试很简单。

import os
import re

# regular expression to match YYYYMMDD timestamps (but not embedded in
# other numbers like 2201703011).
timestamp_check = re.compile(re.compile(r"[^\d]?[12]\d3[01]\d[0123]\d")).search

# Option 1: Stop searching a subtree if pattern is found
A_list = []
for root, dirs, files in os.walk(pathname):
    if timestamp_check(os.path.basename(root)) and 'A' in dirs:
        A_list.append(os.path.join(root, A))
        # inplace modification of `dirs` trims subtree search
        del dirs[:]

# Option 2: Search entire tree, even if matches found
A_list = [os.path.join(root, 'A') 
    for root, dirs, files in os.walk(pathname) 
    if timestamp_check(os.path.basename(root)) and 'A' in dirs]