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

标签 python file

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

c:\test  // process this
c:\test\pics // do not process this
c:\test2 // process this

我如何判断(跨平台)路径不是另一个路径的子目录。最好我希望它是跨平台的,只要符号链接(symbolic link)不是周期性的,我就不担心它们(更糟糕的情况是我最终处理了两次数据)。

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

   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)

最佳答案

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

关于python - 如何确定路径是否是另一个路径的子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8854421/

相关文章:

python - 为什么使用整数作为 pymongo 的键不起作用?

python - 使用python for CGI的问题

python - 计算团队获胜的概率

c++ - 从自己的程序中获取程序元数据

java - 在java中是否有可能知道执行jar时指定的输出文件?

android - 用户尝试从图库中删除文件时的 Intent

python - 在多维环中均匀采样,无排斥

python - 在 python 中验证 SAML 签名

java - 使用java,从文件夹位置提取列表文件名的最资源有效的方法是什么

ios AFDownloadRequestOperation 我用了,为什么启动界面没 react