How To Stop Traversing Current Root And Iterate To The Next One
I'm writing a simple function that walks through a directory tree looking for folders of a certain name. What I'm after is a match's parent path. E.g., for 'C:/a/b/c/MATCH' I want
Solution 1:
Trim dirnames
to an empty list to prevent further traversing of directories below the current one:
defFindProjectSubfolders(masterPath, projectSubfolders):
for currRoot, dirnames, filenames in os.walk(masterPath):
# check if have a project subfolder
foundMatch = Falsefor dirname in dirnames:
for projectSubfolder in projectSubfolders:
if (dirname == projectSubfolder):
foundMatch = True;
breakif (foundMatch == True):
# what goes here to stop traversing "currRoot"# and iterate to the next one?
dirnames[:] = [] # replace all indices in `dirnames` with the empty list
Note that the above code alters the list dirnames
refers to with a slice assignment, it does not rebind dirnames
to a new list.
Post a Comment for "How To Stop Traversing Current Root And Iterate To The Next One"