2017-06-06 64 views
2

需要获取路径中斜线后的最后一个文件夹或元素。换句话说,我有:是否有可能取走路径中的最后一个文件夹?

path = '/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/' 

,我需要得到:

'thumbnails_features_deduped_sample' 
从中

for d, _, files in os.walk(path): 
    print(d[4]) # would be great to have something like this.. 

如何做得很好,也许有人知道吗?

非常感谢。

+0

我敢肯定,你会得到一个更全面回答,但看看os.path - 这正是这种操作。 – xorsyst

回答

10

是的,这是可能的:

使用os.path.basename

>>> os.path.basename('/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/') 
'thumbnails_features_deduped_sample' 

您还可以使用normpath,以适应后/

>>> os.path.basename(os.path.normpath('/Users/ivanmac/Desktop/dogs_vs_cel/thumbnails_features_deduped_sample/')) 
相关问题