os.walk在第一次发现后停止查看子目录

时间:2017-04-25 18:52:34

标签: python python-2.7 os.walk

我需要在目录中首次出现repository.config文件,然后停止查看子目录。

这是我的目录树:

./WAS80/base/disk1/ad/repository.config
./WAS80/base/disk1/md/repository.config
./WAS80/base/disk2/ad/repository.config
./WAS80/base/disk3/ad/repository.config
./WAS80/base/disk4/ad/repository.config
./WAS80/base/repository.config
./WAS80/fixpack/fp5/repository.config
./WAS80/fixpack_suplements/fp5/repository.config
./WAS80/supplements/disk1/ad/repository.config
./WAS80/supplements/disk1/md/repository.config
./WAS80/supplements/disk2/ad/repository.config
./WAS80/supplements/disk3/ad/repository.config
./WAS80/supplements/disk4/ad/repository.config
./WAS80/supplements/repository.config

我需要粗体的那些并停止查看子目录。

我开始修改这段代码,但我无法理解。

pattern='repository.config'
path='/opt/was_binaries'

    def find_all(name, path):
            result = []
            for root, dirs, files in os.walk(path):
                    if name in files:
                            result.append(os.path.join(root, name))
                            continue

            return result

2 个答案:

答案 0 :(得分:5)

这应该做你想要的:

import os

res = []

for here, dirs, files in os.walk(startdir, topdown=True):
    if 'repository.config' in files:
        res.append(os.path.join(here, 'repository.config'))
        dirs[:] = []

print(res)

每当遇到'repository.config'文件时,请将dirs设置为[],以防止os.walk进一步降级到该目录树。

答案 1 :(得分:2)

首先,您必须确保topdown设置为True(这是默认设置),以便在子目录之前扫描父目录

创建existing set()以记住在成功找到配置文件时您遍历的目录。

然后,当您在列表中找到您的文件名时:

  • 检查文件目录是否不是您注册的目录的子项
  • 如果不是,请记下existing中文件的路径(添加os.sep,这样就不会匹配以当前目录名开头的目录的子字符串了相同级别:即使path\to\dir2已经path\to\dir已经set,也应该扫描path\to\dir\subdir。但import os existing = set() for root,dirs,files in os.walk(path,topdown=True): if any(root.startswith(r) for r in existing): # current directory is longest and contains a previously added directory: skip continue if "repository.config" in files: # ok, we note down root dir (+ os.sep to avoid filtering siblings) and print the result existing.add(root+os.sep) print(os.path.join(root,"repository.config")) 将被成功过滤掉。

代码:

<a class = "classicbtn">Sign Up</a>