简体   繁体   English

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

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

In , suppose I have a path like this:中,假设我有这样的路径:

/folderA/folderB/folderC/folderD/

How can I get just the folderD part?我怎样才能得到folderD部分?

Use os.path.normpath , then os.path.basename :使用os.path.normpath ,然后使用os.path.basename

>>> os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
'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 '' .仅使用basename给出最后一个斜杠之后的所有内容,在本例中为''

With python 3 you can use the pathlib module (pathlib.PurePath for example):使用 python 3,您可以使用pathlib模块(例如pathlib.PurePath ):

>>> import pathlib

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

If you want the last folder name where a file is located:如果您想要文件所在的最后一个文件夹名称:

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

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. UPDATE1:如果你给它/folderA/folderB/folderC/folderD/xx.py,这种方法有效。 This gives xx.py as the basename.这将 xx.py 作为基本名称。 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 '/'. UPDATE2:正如 lars 指出的那样,进行更改以适应尾随的“/”。

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

Here is my approach:这是我的方法:

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

I was searching for a solution to get the last foldername where the file is located, I just used split two times, to get the right part.我正在寻找一种解决方案来获取文件所在的最后一个文件夹名称,我只使用了两次split来获得正确的部分。 It's not the question but google transfered me here.这不是问题,但谷歌将我转移到这里。

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

I like the parts method of Path for this:我喜欢 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}')

If you use the native python package pathlib it's really simple.如果您使用本机 python 包pathlib ,它真的很简单。

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

Suppose you have the path to a file in folderD.假设您有文件夹 D 中文件的路径。

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

A naive solution(Python 2.5.2+): 一个幼稚的解决方案(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:]

During my current projects, I'm often passing rear parts of a path to a function and therefore use the Path module.在我目前的项目中,我经常将路径的后部传递给函数,因此使用Path模块。 To get the n-th part in reverse order, I'm using:为了以相反的顺序获得第 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"

Furthermore, to pass the n-th part in reverse order of a path containing the remaining path, I use:此外,要以包含剩余路径的路径的相反顺序传递第 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"

Note that this function returns a Path object which can easily be converted to a string (eg str(path) )请注意,此函数返回一个Path对象,该对象可以轻松转换为字符串(例如str(path)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM