问题
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 "C:/a/b/c". I don't need duplicate parents or paths to subfolder matches, so if there's a "C:/a/b/c/d/e/f/MATCH", I don't need it. So, during my walk, once I have a parent, I want to iterate to the next current root.
Below is what I have so far, including a comment where I'm stuck.
def FindProjectSubfolders(masterPath, projectSubfolders):
for currRoot, dirnames, filenames in os.walk(masterPath):
# check if have a project subfolder
foundMatch = False
for dirname in dirnames:
for projectSubfolder in projectSubfolders:
if (dirname == projectSubfolder):
foundMatch = True;
break
if (foundMatch == True):
# what goes here to stop traversing "currRoot"
# and iterate to the next one?
回答1:
Trim dirnames
to an empty list to prevent further traversing of directories below the current one:
def FindProjectSubfolders(masterPath, projectSubfolders):
for currRoot, dirnames, filenames in os.walk(masterPath):
# check if have a project subfolder
foundMatch = False
for dirname in dirnames:
for projectSubfolder in projectSubfolders:
if (dirname == projectSubfolder):
foundMatch = True;
break
if (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.
来源:https://stackoverflow.com/questions/17785647/how-to-stop-traversing-current-root-and-iterate-to-the-next-one