Python Glob.glob:通配符,表示根目录和目标目录之间的目录数 [英] Python Glob.glob: a wildcard for the number of directories between the root and the destination

查看:85
本文介绍了Python Glob.glob:通配符,表示根目录和目标目录之间的目录数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Okay I'm having trouble not only with the problem itself but even with trying to explain my question. I have a directory tree consisting of about 7 iterations, so: rootdir/a/b/c/d/e/f/destinationdir

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

The thing is some may have 5 subdirectory levels and some may have as many as ten, such as:

rootdir/a/b/c/d/destinationdir

或:

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

它们唯一的共同点是目标目录始终被命名为同一事物.我使用glob函数的方式如下:

The only thing they have in common is that the destination directory is always named the same thing. The way I'm using the glob function is as follows:

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

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

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

However, this only works for the directories with that precise number of intermediate subdirectories. Is there any way for me not to have to specify that number of subdirectories(asterices); in other words having the function arrive at the destinationdir no matter what the number of intermediate subdirectories is, and allowing me to iterate through them. Thanks a lot!

推荐答案

我认为使用os.walk可以更轻松地做到这一点:

I think this could be done more easily with 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)

当然,这不允许您在文件名部分使用glob表达式,但是您可以使用regex或fnmatch来检查这些内容.

Of course, this doesn't allow you to have a glob expression in the filename portion, but you could check that stuff using regex or fnmatch.

编辑

或查找目录:

def find_files(root,d):
    for directory,subdirs,files in os.walk(root):
        if d in subdirs:
            yield os.join(root,directory,d)

这篇关于Python Glob.glob:通配符,表示根目录和目标目录之间的目录数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆