手术室步行在第一次查找后停止查找子目录

2024-05-23 15:30:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我要第一次看到存储库.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

我需要粗体字的,不要在子目录中查找。在

我开始修改这些代码,但是我搞不懂。在

^{pr2}$

Tags: 文件目录configbaserepositorymdadfp5
2条回答

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

创建一个existingset(),以记住在成功找到配置文件时所遍历的目录。在

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

  • 检查文件的目录是否不是您注册的目录的子目录
  • 如果不是,只需记下existing(addos.sep)中文件的路径,这样就不会匹配以当前目录名开头的目录的子字符串:ex: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"))

这应该是您想要的:

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设置为[],以防止{a1}进一步下降到该目录树中。在

相关问题 更多 >