Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a path prefix in python?

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

I want to remove everything before the wa path.

p = path.split('/')
counter = 0
while True:
    if p[counter] == 'wa':
        break
    counter += 1
path = '/'+'/'.join(p[counter:])

For instance, I want '/book/html/wa/foo/bar/' to become '/wa/foo/bar/'.

like image 703
Natim Avatar asked Jan 01 '12 12:01

Natim


People also ask

How do I remove a prefix from a path in Python?

There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .

How do you truncate a path in Python?

truncate() method in Python is used to truncate the file indicated by the specified path to at most specified length. Parameters: path: A path-like object representing a file system path.

What is remove prefix?

removeprefix(prefix, /) function which removes the prefix and returns the rest of the string. If the prefix string is not found then it returns the original string. It is introduced in Python 3.9. 0 version. Syntax: str.removeprefix(prefix, /)


3 Answers

A better answer would be to use os.path.relpath:

http://docs.python.org/3/library/os.path.html#os.path.relpath

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> relative_path = '/book/html'
>>> print(os.path.relpath(full_path, relative_path))
'wa/foo/bar'
like image 81
Mitch ミッチ Avatar answered Oct 23 '22 07:10

Mitch ミッチ


>>> path = '/book/html/wa/foo/bar/'
>>> path[path.find('/wa'):]
'/wa/foo/bar/'
like image 24
Felix Loether Avatar answered Oct 23 '22 07:10

Felix Loether


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 "<stdin>", line 1, in <module>
  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.

like image 33
pjgranahan Avatar answered Oct 23 '22 06:10

pjgranahan