pepero pepero - 10 months ago 57
Python Question

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

In Python, suppose I have a path like this:


How can I get just the

Answer Source

Use os.path.normpath, then os.path.basename:

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

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