我怎样才能递归地找到包含某种类型文件的*目录*?

How can I recursively find the *directories* containing a file of a certain type?

我有一组 .bam,文件分散在文件夹树中。并非每个目录都包含这样的文件。我知道如何使用 glob 递归获取文件本身的路径,但不知道包含它们的目录。

import glob2
bam_files = glob2.glob('/data2/**/*.bam')
print bam_files

上面的代码给出了 .bam 文件,但我只想要文件夹。想知道是否有一种直接的方法可以使用不带正则表达式的 glob 来做到这一点。

使用一组 os.path.dirname() [https://docs.python.org/2/library/os.path.html#os.path.dirname]:

import glob2
import os 
bam_dirs = {os.path.dirname(p) for p in glob2.glob('/data2/**/*.bam')}
print bam_dirs