获取目录的姓氏:
str = "/folderA/folderB/folderC/folderD"
editstr = str.split("/")[-1]
print(editstr)
folderD
如何在folderD
之前获取所有目录(没有最后一个斜杠)? E.g:
editstr = ???
print(editstr)
/folderA/folderB/folderC
答案 0 :(得分:2)
>>> import os
>>> s = "/folderA/folderB/folderC/folderD"
>>> os.path.basename(s)
'folderD'
>>> os.path.dirname(s)
'/folderA/folderB/folderC'
答案 1 :(得分:1)
您可以使用str.rsplit()
:
>>> editstr = str.rsplit('/folderD', 1)[0]
>>> print(editstr)
/folderA/folderB/folderC