在python中以递归方式搜索通配符文件夹

时间:2011-08-08 18:55:45

标签: python

你好我试着做一些像

这样的事情
// 1. for x in glob.glob('/../../nodes/*/views/assets/js/*.js'):
// 2 .for x in glob.glob('/../../nodes/*/views/assets/js/*/*.js'):
    print x

有什么办法可以回避搜索吗?

我已经查看了Use a Glob() to find files recursively in Python?,但 os.walk在节点和视图之间不接受上面的通配符文件夹,以及那些非常有用的http://docs.python.org/library/glob.html文档。

感谢

3 个答案:

答案 0 :(得分:9)

警告:这也将选择与根文件夹下的任何位置匹配的任何文件,即节点/。

import os, fnmatch

def locate(pattern, root_path):
    for path, dirs, files in os.walk(os.path.abspath(root_path)):
        for filename in fnmatch.filter(files, pattern):
            yield os.path.join(path, filename)

由于os.walk不接受通配符,我们走树并过滤我们需要的东西。

js_assets = [js for js in locate('*.js', '/../../nodes')]

locate函数生成一个与模式匹配的所有文件的迭代器。

替代解决方案:您可以尝试extended glob,它会将递归搜索添加到glob。

现在你可以写一个更简单的表达式,如:

fnmatch.filter( glob.glob('/../../nodes/*/views/assets/js/**/*'), '*.js' )

答案 1 :(得分:2)

我在这里回答了类似的问题:fnmatch and recursive path match with `**`

你可以使用glob2或formic,两者都可以通过easy_install或pip获得。

GLOB2

FORMIC

你可以在这里找到它们: Use a Glob() to find files recursively in Python?

我经常使用glob2,例如:

import glob2
files = glob2.glob(r'C:\Users\**\iTunes\**\*.mp4')

答案 2 :(得分:1)

为什么不将你的野外路径分成多个部分,例如:

parent_path = glob.glob('/../../nodes/*')
for p in parent_path:
    child_paths = glob.glob(os.path.join(p, './views/assets/js/*.js'))
    for c in child_paths:
        #do something

您可以使用要检索的子资源列表替换上述部分内容。

或者,如果您的环境提供了find命令,则可以为此类任务提供更好的支持。如果你在Windows中,可能会有一个类似的程序。

相关问题