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

/folderA/folderB/folderC/folderD/

我怎样才能得到folderD部分?


当前回答

你可以这样做

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

其他回答

你可以这样做

>>> 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'
path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()

在我目前的项目中,我经常将路径的后面部分传递给函数,因此使用path模块。为了得到第n部分的倒序,我使用:

from typing import Union
from pathlib import Path

def get_single_subpath_part(base_dir: Union[Path, str], n:int) -> str:
    if n ==0:
        return Path(base_dir).name
    for _ in range(n):
        base_dir = Path(base_dir).parent
    return getattr(base_dir, "name")

path= "/folderA/folderB/folderC/folderD/"

# for getting the last part:
print(get_single_subpath_part(path, 0))
# yields "folderD"

# for the second last
print(get_single_subpath_part(path, 1))
#yields "folderC"

此外,为了以包含剩余路径的路径的相反顺序传递第n部分,我使用:

from typing import Union
from pathlib import Path

def get_n_last_subparts_path(base_dir: Union[Path, str], n:int) -> Path:
    return Path(*Path(base_dir).parts[-n-1:])

path= "/folderA/folderB/folderC/folderD/"

# for getting the last part:
print(get_n_last_subparts_path(path, 0))
# yields a `Path` object of "folderD"

# for second last and last part together 
print(get_n_last_subparts_path(path, 1))
# yields a `Path` object of "folderc/folderD"

注意,这个函数返回一个可以很容易地转换为字符串的Pathobject(例如str(path))

在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'
str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]