Python: Get relative path from comparing two absolute paths

后端 未结 6 1954
南笙
南笙 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:35

    Edit : See jme's answer for the best way with Python3.

    Using pathlib, you have the following solution :

    Let's say we want to check if son is a descendant of parent, and both are Path objects. We can get a list of the parts in the path with list(parent.parts). Then, we just check that the begining of the son is equal to the list of segments of the parent.

    >>> lparent = list(parent.parts)
    >>> lson = list(son.parts)
    >>> if lson[:len(lparent)] == lparent:
    >>> ... #parent is a parent of son :)
    

    If you want to get the remaining part, you can just do

    >>> ''.join(lson[len(lparent):])
    

    It's a string, but you can of course use it as a constructor of an other Path object.

提交回复
热议问题