简体   繁体   English

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

[英]search in wildcard folders recursively in python

hello im trying to do something like 你好我试着做点什么

// 1. for x in glob.glob('/../../nodes/*/views/assets/js/*.js'):
// 2 .for x in glob.glob('/../../nodes/*/views/assets/js/*/*.js'):
    print x

is there anything can i do to search it recuresively ? 有什么办法可以回忆搜索吗?

i already looked into Use a Glob() to find files recursively in Python? 我已经研究过使用Glob()在Python中递归查找文件? but the os.walk dont accept wildcards folders like above between nodes and views, and the http://docs.python.org/library/glob.html docs that dosent help much. 但是os.walk不接受节点和视图之间的上面的通配符文件夹 ,以及http://docs.python.org/library/glob.html那些非常有用的文档。

thanks 谢谢

Caveat: This will also select any files matching the pattern anywhere beneath the root folder which is 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)

As os.walk does not accept wildcards we walk the tree and filter what we need. 由于os.walk不接受通配符,我们走树并过滤我们需要的东西。

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

The locate function yields an iterator of all files which match the pattern. locate函数产生与模式匹配的所有文件的迭代器。

Alternative solution: You can try the extended glob which adds recursive searching to glob. 替代解决方案:您可以尝试扩展的glob ,它会向glob添加递归搜索。

Now you can write a much simpler expression like: 现在你可以写一个更简单的表达式,如:

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

I answered a similar question here: fnmatch and recursive path match with `**` 我在这里回答了一个类似的问题: fnmatch和递归路径匹配`**`

You could use glob2 or formic, both available via easy_install or pip. 您可以使用glob2或formic,两者都可以通过easy_install或pip获得。

GLOB2 GLOB2

FORMIC FORMIC

You can find them both mentioned here: Use a Glob() to find files recursively in Python? 您可以在这里找到它们: 使用Glob()在Python中递归查找文件?

I use glob2 a lot, ex: 我经常使用glob2,例如:

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

Why don't you split your wild-carded paths into multiple parts, like: 为什么不将野外梳理路径分成多个部分,例如:

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

You can replace some of the above with a list of child assets that you want to retrieve. 您可以使用要检索的子资产列表替换上面的一些内容。

Alternatively, if your environment provides the find command, that provides better support for this kind of task. 或者,如果您的环境提供了find命令,则可以为此类任务提供更好的支持。 If you're in Windows, there may be an analogous program. 如果你在Windows中,可能会有一个类似的程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM