简体   繁体   中英

Use os.path to remove element in path

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?

isn't what os.path.relpath does ?

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

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 (ie slice first element), while second - joins them back to string.

Ie

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM