如何只获取Python中路径的最后一部分?

时间:2010-10-13 15:03:16

标签: python path path-manipulation

在Python中,假设我有这样的路径:

/folderA/folderB/folderC/folderD/

如何才能获得folderD部分?

11 个答案:

答案 0 :(得分:294)

使用os.path.normpath,然后os.path.basename

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

第一个剥离任何尾部斜杠,第二个为您提供路径的最后一部分。仅使用basename会提供最后一个斜杠之后的所有内容,在本例中为''

答案 1 :(得分:18)

你可以做到

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

答案 2 :(得分:12)

这是我的方法:

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

答案 3 :(得分:6)

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

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

答案 4 :(得分:3)

使用python 3,您可以使用pathlib模块(例如pathlib.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'

答案 5 :(得分:1)

天真的解决方案(Python 2.5.2 +):

s="/path/to/any/folder/orfile"
desired_dir_or_file = s[s.rindex('/',0,-1)+1:-1] if s.endswith('/') else s[s.rindex('/')+1:]

答案 6 :(得分:1)

如果您使用包 pathlib,那真的很简单。

>>> from pathlib import Path
>>> your_path = Path("/folderA/folderB/folderC/folderD/")
>>> your_path.stem
'folderD'

假设您有文件夹 D 中文件的路径。

>>> from pathlib import Path
>>> your_path = Path("/folderA/folderB/folderC/folderD/file.txt")
>>> your_path.stem
'file.txt'
>>> your_path.parent
'folderD'

答案 7 :(得分:0)

path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()

答案 8 :(得分:0)

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

答案 9 :(得分:0)

为此,我喜欢Path的parts方法:

grandparent_directory, parent_directory, filename = Path(export_filename).parts[-3:]
log.info(f'{t: <30}: {num_rows: >7} Rows exported to {grandparent_directory}/{parent_directory}/{filename}')

答案 10 :(得分:0)

在我当前的项目中,我经常将路径的后部传递给函数,因此使用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"

请注意,此函数返回一个Path对象,该对象可以轻松转换为字符串(例如str(path)