Python 3按名称过滤目录,匹配特定模式

use*_*632 4 python regex directory filtering python-3.x

目前我正在开发将执行特定目录清理的脚本.

例如:目录:/ app/test/log包含许多名称为testYYYYMMDD和logYYYYMMDD的子目录

我需要的是过滤掉像testYYYYMMDD这样的目录

要获取具有给定目录中的绝对路径的所有文件夹,我使用:

folders_in_given_folder = [name for name in os.listdir(Directory) if os.path.isdir(os.path.join(Directory, name))]
folder_list = []
for folder in folders_in_given_folder:
    folder_list.append([os.path.join(Directory, folder)])
print(folder_list)
Run Code Online (Sandbox Code Playgroud)

给出输出:

[['/app/test/log/test20150615'], ['/app/test/log/test20150616'], ['/app/test/log/b'], ['/app/test/log/a'], ['/app/test/log/New folder'], ['/app/test/log/rem'], ['/app/test/log/test']]
Run Code Online (Sandbox Code Playgroud)

所以现在我需要过滤掉适合模式的子目录,模式可以是:*test*,test*,test2015*

我尝试过使用glob.glob(),但这似乎只适用于文件而不是目录.

有人可以这么善良并解释我如何取得理想的结果吗?

Azu*_*ree 6

import os 
import re

result = []
reg_compile = re.compile("test\d{8}")
for dirpath, dirnames, filenames in os.walk(myrootdir):
    result = result + [dirname for dirname in dirnames if  reg_compile.match(dirname)]
Run Code Online (Sandbox Code Playgroud)

我建议我解释一下(感谢-1顺便说一下:D)

compile("test\d{8})会准备名为任何文件夹相匹配的正则表达式test,然后用一个8位数字格式的日期.

然后我利用该os.walk方法在folders迭代器中正确地拥有每个文件夹(从而避免使用该方法is_dir)

使用该行[dirname for dirname in dirnames if reg_compile.match(dirname)]我过滤名称与上面说明的正则表达式匹配的文件夹.

对于第一个答案(是的,它是第一个)有效(在我的计算机上测试python2和python3),我发现它很苛刻.接受的答案也包含我使用的相同类型的正则表达式.现在我也同意我应该先解释过.

你愿意去除那个downvote吗?