91

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/'.

Natim
  • 17,274
  • 23
  • 92
  • 150

4 Answers4

230

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'
Community
  • 1
  • 1
Mitch ミッチ
  • 2,382
  • 2
  • 13
  • 5
  • 12
    This is a much better answer because it avoids any issues with different path separators. – intrepidhero Sep 18 '15 at 22:59
  • 1
    Totally agree with @intrepidhero's comment, plus this works whether or not `full_path` contains the trailing `/` character or not—so it's even more general than that. – martineau Dec 10 '18 at 10:50
36

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.

pjgranahan
  • 575
  • 6
  • 15
  • 1
    While the `pathlib` module is very "user friendly", it wasn't created until very late in the game. Personally I still prefer using `os.path.relpath()` as shown in the [accepted answer](https://stackoverflow.com/a/19856910/355230) because it will work in most versions of Python (including Python 2). – martineau Dec 10 '18 at 10:45
27
>>> path = '/book/html/wa/foo/bar/'
>>> path[path.find('/wa'):]
'/wa/foo/bar/'
Felix Loether
  • 6,010
  • 2
  • 32
  • 23
0
import re

path = '/book/html/wa/foo/bar/'
m = re.match(r'.*(/wa/[a-z/]+)',path)
print m.group(1)
vivek
  • 4,951
  • 4
  • 25
  • 33
  • This helps for my second question which was how to remove the last path if it is a integer. Nice :) – Natim Jan 01 '12 at 12:32