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

后端 未结 9 520
长发绾君心
长发绾君心 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条回答
  •  -上瘾入骨i
    2020-11-28 19:36

    During my current projects, I'm often passing rear parts of a path to a function and therefore use the Path module. To get the n-th part in reverse order, I'm using:

    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:

    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 Pathobject which can easily be converted to a string (e.g. str(path))

提交回复
热议问题