How to remove a path prefix in python?

Natim picture Natim · Jan 1, 2012 · Viewed 46.3k times · Source

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

Answer

Mitch ミッチ picture Mitch ミッチ · Nov 8, 2013

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

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

>>> import os
>>> full_path = '/book/html/wa/foo/bar/'
>>> print os.path.relpath(full_path, '/book/html')
'wa/foo/bar'