0

I want to use os.path to safely remove the first element from a given path:

/foo/bar/something
/foo/something
/foo/foo

So, if foo is in the the path, I want to remove it. I know I could do this regex but I would rather use os.path if possible.

However, I've been through the doc page and can't see how it offers any methods to do this.

Is there a way, or should I just regex it?

0

3 Answers 3

4

isn't what os.path.relpathdoes ?

>>> a="/foo/bar/boz" 
>>> import os 
>>> os.path.relpath(a, '/foo')
'bar/boz'
1

Take a look at str.split with os.sep as argument and os.path.join. First will split path into parts (foo, bar, something), so you can apply any list operation to them (i.e. slice first element), while second - joins them back to string.

I.e.

import os

paths = ['/foo/bar/something',
        '/foo/something',
        '/foo/foo',
        'foo/spam/ham']

for path in paths:
    parts = path.split(os.sep)

    # For absolute paths - first item would be empty string, 
    # ignore it
    firstidx = 0 if parts[0] else 1
    if parts[firstidx] == 'foo':
        parts.pop(firstidx)

    print os.path.join(*parts)
0

The question is a bit confusing—I take is as if you'd like to remove every occurence of “foo” in a given path.

import os
paths = ['/foo/bar/something', '/foo/something', '/foo/foo']
remove_item = 'foo'
for path in paths:
    new_path = os.sep.join([item for item in path.split(os.sep) if item != remove_item])
    print(new_path)

Not the answer you're looking for? Browse other questions tagged or ask your own question.