pythonpathpath-manipulation

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


In , suppose I have a path like this:

/folderA/folderB/folderC/folderD/

How can I get just the folderD part?


Solution

  • 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 ''.