>>> 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'
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.
The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename gives everything after the last slash, which in this case is ''.
You could do
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 -
UPDATE2: As lars pointed out, making changes so as to accomodate trailing '/'.
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.
Use
os.path.normpath
, thenos.path.basename
:The first strips off any trailing slashes, the second gives you the last part of the path. Using only
basename
gives everything after the last slash, which in this case is''
.A naive solution(Python 2.5.2+):