Vingtoft
Vingtoft

Reputation: 14606

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?

Upvotes: 3

Views: 9178

Answers (2)

Mike Müller
Mike Müller

Reputation: 85442

You can use os.path.basename:

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

Upvotes: 12

VlassisFo
VlassisFo

Reputation: 660

Maybe you could try this:

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

Which is the last item in the list

Upvotes: 2

Related Questions