Rawan
Rawan

Reputation: 403

How to extract subpath from a file path by python?

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

Answers (2)

j__carlson
j__carlson

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

Wander Nauta
Wander Nauta

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

Related Questions