1

我正在编写一个简单的函数,它遍历目录树以查找特定名称的文件夹。我所追求的是匹配的父路径。例如,对于“C:/a/b/c/MATCH”,我想要“C:/a/b/c”。我不需要重复的父项或子文件夹匹配的路径,所以如果有“C:/a/b/c/d/e/f/MATCH”,我不需要它。所以,在我走路的过程中,一旦我有了父母,我想迭代到下一个当前根。

以下是我到目前为止的内容,包括我被卡住的评论。

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?
4

1 回答 1

2

修剪dirnames到一个空列表以防止进一步遍历当前目录下面的目录:

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

请注意,上面的代码dirnames使用切片分配更改了列表引用,它不会重新绑定dirnames到新列表。

于 2013-07-22T10:53:09.033 回答