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

2024-06-01 13:13:31 发布

您现在位置: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文档有很大帮助。

谢谢


Tags: toinforosusejsfilesfind
3条回答

你为什么不把你的野性之路分成多个部分,比如:

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中,可能有一个类似的程序。

我在这里回答了一个类似的问题: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')

注意:这还将选择与根文件夹nodes/下的模式匹配的任何文件。

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' )

相关问题 更多 >