2017-06-06 35 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/')) 
相關問題