Python: Get relative path from comparing two absolute paths

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

    A write-up of jme's suggestion, using pathlib, in Python 3.

    from pathlib import Path
    parent = Path(r'/a/b')
    son = Path(r'/a/b/c/d')            
    ​
    if parent in son.parents or parent==son:
        print(son.relative_to(parent)) # returns Path object equivalent to 'c/d'
    

提交回复
热议问题