Python在特定目录模式中搜索文件名模式

时间:2013-12-03 14:35:05

标签: python pattern-matching filenames directory-traversal

我如何使用os.walk(或任何其他方式)进行搜索,以便我可以在根目录下的某些模式的目录下找到具有特定名称的文件

我的意思是,如果我有一个目录d:\ installedApps,我在其下面有a.ear,b.ear,... x.ear,y.ear,z.ear目录以及其他目录我希望只在根目录下的* .ear子目录下搜索文件模式web * .xml而不遍历同一级别的其他目录,我该怎么做?

我尝试了各种方式(有些方法在本网站上使用其他一些例子,例如walklevel示例等),但我没有得到我想要的结果。

更新

我尝试使用此网站的walkdepth代码段并尝试将其合并到嵌套循环中但不起作用

这是我试过的代码

import os, os.path
import fnmatch

def walk_depth(root, max_depth):
    print 'root in walk_depth : ' + root
    # some initial setup for getting the depth
    root = os.path.normpath(root)
    depth_offset = root.count(os.sep) - 1

    for root, dirs, files in os.walk(root, topdown=True):
        yield root, dirs, files
        # get current depth to determine if we need to stop
        depth = root.count(os.sep) - depth_offset
        if depth >= max_depth:
            # modify dirs so we don't go any deeper
            dirs[:] = []

for root, dirs, files in walk_depth('D:\installedApps', 5):
    for dirname in dirs:
        if fnmatch.fnmatch(dirname, '*.ear'):
            print 'dirname : ' + dirname
            root2 = os.path.normpath(dirname)
            for root2, dir2, files2 in walk_depth(root2, 5):
                for filename in files2:
                    if fnmatch.fnmatch(filename, 'webservices.xml'):
                        print '\tfilename : ' + filename

1 个答案:

答案 0 :(得分:2)

我强烈建议你看看这个答案。有三种不同的解决方案,但#1似乎最准确地匹配您要做的事情。

Find all files in a directory with extension .txt in Python

编辑我刚刚发现了一些关于可以完成这项工作的glob类的更多信息。

来自Python文档

  

glob.glob(路径)

     

返回与路径名匹配的可能为空的路径名列表   必须是包含路径规范的字符串。 pathname可以   绝对的(如/usr/src/Python-1.5/Makefile)或亲戚(如   ../../Tools//.gif),并且可以包含shell样式的通配符。破碎   符号链接包含在结果中(如在shell中)。

所以你可以按照以下方式做点什么:

def getFiles(path):
    answer = []
    endPaths = glob.glob(path + "web*.xml")
    answer += endPaths
    if len(glob.glob(path + "*ear/")) > 0:
            answer += getFiles(path + "*ear/")

    return answer

filepaths = getFiles("./")
print(filepaths

我实际测试了那个,它在我认为按照你想要的方式设置的目录中运行得非常好。

相关问题