如何确定路径是否是另一个路径的子目录?

esa*_*sac 6 python file

我得到了一个路径列表,我需要检查其中的文件.当然,如果给我一个root和一个子目录,则不需要处理子目录.例如

c:\test  // process this
c:\test\pics // do not process this
c:\test2 // process this
Run Code Online (Sandbox Code Playgroud)

如何判断(跨平台)路径不是另一个路径的子目录.我希望这是跨平台的,并且我不担心符号链接,只要它们不是循环的(更糟糕的是我最终处理数据两次).

更新:这是我最终使用的代码,感谢@FJ

   def unique_path_roots(paths):
    visited = set()
    paths = list(set(paths))

    for path in sorted(paths,key=cmp_to_key(locale.strcoll)):
        path = normcase(normpath(realpath(path)))

        head, tail = os.path.split(path)
        while head and tail:
            if head in visited:
                break
            head, tail = os.path.split(head)
        else:
            yield path
            visited.add(path)
Run Code Online (Sandbox Code Playgroud)

jgo*_*ers 8

def is_subdir(path, directory):
    path = os.path.realpath(path)
    directory = os.path.realpath(directory)

    relative = os.path.relpath(path, directory)

    if relative.startswith(os.pardir):
        return False
    else:
        return True
Run Code Online (Sandbox Code Playgroud)


And*_*ark 7

我将维护一组您已经处理过的目录,然后为每个新路径检查在处理之前是否已经存在该组中的任何父目录:

import os.path

visited = set()
for path in path_list:
    head, tail = os.path.split(path)
    while head and tail:
        if head in visited:
            break
        head, tail = os.path.split(head)
    else:
        process(path)
        visited.add(path)
Run Code Online (Sandbox Code Playgroud)

请注意,path_list应对其进行排序,以便子目录始终位于其父目录之后(如果存在).