Python: Get relative path from comparing two absolute paths

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

    os.path.relpath:

    Return a relative filepath to path either from the current directory or from an optional start point.

    >>> from os.path import relpath
    >>> relpath('/usr/var/log/', '/usr/var')
    'log'
    >>> relpath('/usr/var/log/', '/usr/var/sad/')
    '../log'
    

    So, if relative path starts with '..' - it means that the second path is not descendant of the first path.

    In Python3 you can use PurePath.relative_to:

    Python 3.5.1 (default, Jan 22 2016, 08:54:32)
    >>> from pathlib import Path
    
    >>> Path('/usr/var/log').relative_to('/usr/var/log/')
    PosixPath('.')
    
    >>> Path('/usr/var/log').relative_to('/usr/var/')
    PosixPath('log')
    
    >>> Path('/usr/var/log').relative_to('/etc/')
    Traceback (most recent call last):
      File "", line 1, in 
      File "/usr/local/Cellar/python3/3.5.1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/pathlib.py", line 851, in relative_to
        .format(str(self), str(formatted)))
    ValueError: '/usr/var/log' does not start with '/etc'
    

提交回复
热议问题