How do I get the child folder name of the path besides these methods?
Question:
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?
Answers:
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.
I think you’re looking for pathlib.name
>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.name + "/"
'level3/'
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?
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.
I think you’re looking for pathlib.name
>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.name + "/"
'level3/'