How to stop traversing current root and iterate to the next one

☆樱花仙子☆ 提交于 2020-01-05 06:42:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!