os.walk stop looking on subdirectories after first finding
First, you have to make sure that topdown
is set to True
(this is default) so parent directories are scanned before child directories.
Create an existing
set()
to remember which directories you traversed when successfully found a config file.
Then, when you find your filename in the list:
- check if the directory of the file isn't a child of a directory you registered
- if it's not, just note down the path of the file in
existing
(addos.sep
, so you don't match substrings of directories starting with the current dirname at the same level: ex:path\to\dir2
should be scanned even ifpath\to\dir
is already in theset
. Butpath\to\dir\subdir
will be successfully filtered out).
code:
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"))
this should do what you want:
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)
whenever you encounter a 'repository.config'
file, set dirs
to []
in order to prevent os.walk
from descending further into that directory tree.
note: it is vital for this to work to change the dirs
in-place (i.e. dirs[:] = []
) as opposed to rebind it (dirs = []
).,