[英]How do I get the child folder name of the path besides these methods?
Of the given path like "level1/level2/level3/", I'd like pass it through some operation and get the result like "level3/".在像“level1/level2/level3/”这样的给定路径中,我想通过一些操作并得到像“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.试验 1:在路径 object 中找到
parent
属性后,我寻找接近child
属性的东西,但找不到。
>>> 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:试用 2:我像这样使用
os
模块:
>>> 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?是否有试用 2 的替代方法,或者我可以从
pathlib
package 或Path
class 在试用 1 中进行某些工作吗?
Try using pathlib.parts尝试使用pathlib.parts
>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.parts[-1]
'level3'
You can then append the "/"
character if needed.然后,如果需要,您可以 append 使用
"/"
字符。
I think you're looking for pathlib.name我认为您正在寻找pathlib.name
>>> from pathlib import Path
>>> path = Path("level1/level2/level3/")
>>> path.name + "/"
'level3/'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.