我需要获取目录中第一次出现的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
这应该做你想做的:
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[:] = []
# dirs.clear() # should also work - not tested...
print(res)
每当你遇到一个'repository.config'
文件,设置dirs
to []
为了阻止os.walk https://docs.python.org/3/library/os.html#os.walk从进一步下降到该目录树。
注意:这对于改变现状至关重要dirs
就地(即dirs[:] = []
)而不是重新绑定它(dirs = []
).,
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)