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

后端 未结 9 522
长发绾君心
长发绾君心 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条回答
  • 2020-11-28 19:39

    Use os.path.normpath, then 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 ''.

    0 讨论(0)
  • 2020-11-28 19:42

    I like the parts method of Path for this:

    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}')
    
    0 讨论(0)
  • 2020-11-28 19:43

    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. 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)
    
    0 讨论(0)
提交回复
热议问题