How to remove a path prefix in python?

前端 未结 4 513
走了就别回头了
走了就别回头了 2020-12-28 11:36

I wanted to know what is the pythonic function for this :

I want to remove everything before the wa path.

p = path.split(\'/\')
counter         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-28 12:16

    For Python 3.4+, you should use pathlib.PurePath.relative_to. From the documentation:

    >>> p = PurePosixPath('/etc/passwd')
    >>> p.relative_to('/')
    PurePosixPath('etc/passwd')
    
    >>> p.relative_to('/etc')
    PurePosixPath('passwd')
    
    >>> p.relative_to('/usr')
    Traceback (most recent call last):
      File "", line 1, in 
      File "pathlib.py", line 694, in relative_to
        .format(str(self), str(formatted)))
    ValueError: '/etc/passwd' does not start with '/usr'
    

    Also see this StackOverflow question for more answers to your question.

提交回复
热议问题