4

Of the given path like "level1/level2/level3/", I'd like pass it through some operation and get the result like "level3/". So I made two trials like these:

TRIAL 1: After finding parent property within the Path object, I looked for something close to a child property, but could not.

>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.parent
WindowsPath('level1/level2')
>>> str(path.parent)
'level1\\level2'

TRIAL 2: I used the os module like this:

>>> import os
>>> os.path.basename("level1/level2/level3/".strip("/")) + "/"
'level3/'

Is there an alternative to TRIAL 2, or can I make something work within TRIAL 1 from the pathlib package or Path class?

CDJB
  • 14,043
  • 5
  • 29
  • 55
Kiran Racherla
  • 219
  • 3
  • 12

2 Answers2

3

Try using pathlib.parts

>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.parts[-1]
'level3'

You can then append the "/" character if needed.

Neuron
  • 5,141
  • 5
  • 38
  • 59
CDJB
  • 14,043
  • 5
  • 29
  • 55
0

I think you're looking for pathlib.name

>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.name + "/"
'level3/'