0

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'

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

Comments

0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.