简体   繁体   中英

Python: Extract folder name from path

I have a path as a string in python:

path = "/folder_a/folder_b/folder_c/folder_d"

How can I extract the name of the last folder ("folder_d") from the path ?

You can use os.path.basename :

>>> path = "/folder_a/folder_b/folder_c/folder_d"
>>> import os
>>> os.path.basename(path)
'folder_d'

Maybe you could try this:

y=path.split('/')
last_folder=y[-1]

Which is the last item in the list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM