Python: Get relative path from comparing two absolute paths

后端 未结 6 1950
南笙
南笙 2020-11-27 11:04

Say, I have two absolute paths. I need to check if the location referring to by one of the paths is a descendant of the other. If true, I need to find out the relative path

6条回答
  •  一生所求
    2020-11-27 11:33

    Pure Python2 w/o dep:

    def relpath(cwd, path):
        """Create a relative path for path from cwd, if possible"""
        if sys.platform == "win32":
            cwd = cwd.lower()
            path = path.lower()
        _cwd = os.path.abspath(cwd).split(os.path.sep)
        _path = os.path.abspath(path).split(os.path.sep)
        eq_until_pos = None
        for i in xrange(min(len(_cwd), len(_path))):
            if _cwd[i] == _path[i]:
                eq_until_pos = i
            else:
                break
        if eq_until_pos is None:
            return path
        newpath = [".." for i in xrange(len(_cwd[eq_until_pos+1:]))]
        newpath.extend(_path[eq_until_pos+1:])
        return os.path.join(*newpath) if newpath else "."
    

提交回复
热议问题