Python Glob.glob:通配符,表示根目录和目标目录之间的目录数

Chr*_*dad 5 python glob wildcard path

好的,我不仅在问题本身上遇到麻烦,甚至在尝试解释我的问题时也遇到麻烦。我有一个包含约7次迭代的目录树,因此:rootdir/a/b/c/d/e/f/destinationdir

问题是有些可能具有5个子目录级别,有些可能多达10个子目录级别,例如:

rootdir/a/b/c/d/destinationdir
Run Code Online (Sandbox Code Playgroud)

要么:

rootdir/a/b/c/d/e/f/g/h/destinationdir

他们唯一的共同点是目标目录始终被命名为同一东西。我使用glob函数的方式如下:

for path in glob.glob('/rootdir/*/*/*/*/*/*/destinationdir'):
--- os.system('cd {0}; do whatever'.format(path))

但是,这仅适用于中间子目录数量精确的目录。我有什么办法不必指定那个数目subdirectories(asterices)?换句话说,无论中间子目录有多少,都具有到达目标目录的功能,并允许我遍历它们。非常感谢!

mgi*_*son 5

我认为可以使用以下命令更轻松地完成此操作os.walk

def find_files(root,filename):
    for directory,subdirs,files in os.walk(root):
        if filename in files:
            yield os.join(root,directory,filename)
Run Code Online (Sandbox Code Playgroud)

当然,这不允许您在文件名部分中包含全局表达式,但是您可以使用regex或fnmatch检查这些内容。

编辑

或查找目录:

def find_files(root,d):
    for directory,subdirs,files in os.walk(root):
        if d in subdirs:
            yield os.join(root,directory,d)
Run Code Online (Sandbox Code Playgroud)