Reputation: 403
I'm trying to extract subpath from a list of paths using python:
path structure looks like this:
path= '/a/b/c/d/e/f/g/h/image.png'
This is what I'm looking for:
'f/g/h/image.png'
Upvotes: 0
Views: 1014
Reputation: 1348
This will do the trick:
path= '/a/b/c/d/e/f/g/h/image.png'
cutoff= 6
'/'.join(path.split('/')[cutoff:])
Output:
'f/g/h/image.png'
Upvotes: 0
Reputation: 19625
The relative_to
method on Path works like this. You can use str
to turn the result into a string, if you prefer.
>>> from pathlib import Path
>>> path = Path('/a/b/c/d/e/f/g/h/image.png')
>>> path.relative_to('/a/b/c/d/e')
PosixPath('f/g/h/image.png')
>>> str(_)
'f/g/h/image.png'
Documentation: https://docs.python.org/3/library/pathlib.html#pathlib.PurePath.relative_to
Upvotes: 6