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

编程入门 行业动态 更新时间:2024-10-25 22:26:59
本文介绍了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:通配符,表示根目录和目标目录之间的目录数

本文发布于:2023-10-07 14:41:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1469664.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:目录   通配符   根目录   目标   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!