The Python Oracle

How to get only the last part of a path in Python?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 Question
00:21 Accepted answer (Score 582)
00:48 Answer 2 (Score 109)
01:12 Answer 3 (Score 38)
01:55 Answer 4 (Score 25)
02:12 Thank you

--

Full question
https://stackoverflow.com/questions/3925...

Question links:
[python]: /questions/tagged/python

Accepted answer links:
[os.path.normpath]: https://docs.python.org/library/os.path....
[os.path.basename]: https://docs.python.org/library/os.path....

Answer 2 links:
[pathlib]: https://docs.python.org/3/library/pathli...
[pathlib.PurePath]: https://docs.python.org/3/library/pathli...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #path #pathmanipulation

#avk47



ACCEPTED ANSWER

Score 627


Use os.path.normpath to strip off any trailing slashes, then os.path.basename gives you the last part of the path:

>>> os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
'folderD'

Using only basename gives everything after the last slash, which in this case is ''.




ANSWER 2

Score 40


You could do

>>> import os
>>> os.path.basename('/folderA/folderB/folderC/folderD')

UPDATE1: This approach works in case you give it /folderA/folderB/folderC/folderD/xx.py. This gives xx.py as the basename. Which is not what you want I guess. So you could do this -

>>> import os
>>> path = "/folderA/folderB/folderC/folderD"
>>> if os.path.isdir(path):
        dirname = os.path.basename(path)

UPDATE2: As lars pointed out, making changes so as to accomodate trailing '/'.

>>> from os.path import normpath, basename
>>> basename(normpath('/folderA/folderB/folderC/folderD/'))
'folderD'



ANSWER 3

Score 27


Here is my approach:

>>> import os
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/test.py'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD/'))
folderD
>>> print os.path.basename(
        os.path.dirname('/folderA/folderB/folderC/folderD'))
folderC



ANSWER 4

Score 11


I was searching for a solution to get the last foldername where the file is located, I just used split two times, to get the right part. It's not the question but google transfered me here.

pathname = "/folderA/folderB/folderC/folderD/filename.py"
head, tail = os.path.split(os.path.split(pathname)[0])
print(head + "   "  + tail)