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

后端 未结 9 530
长发绾君心
长发绾君心 2020-11-28 19:01

In Python, suppose I have a path like this:

/folderA/folderB/folderC/folderD/

How can I get just the folderD part?

9条回答
  •  一生所求
    2020-11-28 19:22

    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'
    

提交回复
热议问题