在python中,假设我有一个这样的路径:

/folderA/folderB/folderC/folderD/

我怎样才能得到folderD部分?


当前回答

str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]

其他回答

在python3中,你可以使用pathlib模块(pathlib. python)。例如PurePath):

>>> import pathlib

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/')
>>> path.name
'folderD'

如果您想要文件所在的最后一个文件夹名称:

>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py')
>>> path.parent.name
'folderD'

我正在寻找一个解决方案,以获得文件所在的最后一个文件夹名,我只是使用分裂两次,以获得正确的部分。这不是问题,但谷歌把我调到了这里。

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

以下是我的方法:

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

你可以这样做

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

UPDATE1:如果你给它/folderA/folderB/folderC/folderD/xx.py,这种方法是有效的。这将xx.py作为基名。我猜这不是你想要的。所以你可以这样做-

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

UPDATE2:正如lars指出的那样,进行更改以适应以'/'结尾。

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