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

2019-01-10 05:12发布

In Python, suppose I have a path like this:

/folderA/folderB/folderC/folderD/

How can I get just the folderD part?

7条回答
做个烂人
2楼-- · 2019-01-10 05:43
path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()
查看更多
走好不送
3楼-- · 2019-01-10 05:45

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. This gives xx.py as the basename. 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 '/'.

>>> from os.path import normpath, basename
>>> basename(normpath('/folderA/folderB/folderC/folderD/'))
'folderD'
查看更多
我欲成王,谁敢阻挡
4楼-- · 2019-01-10 05:46
str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]
查看更多
Anthone
5楼-- · 2019-01-10 05:54

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)
查看更多
戒情不戒烟
6楼-- · 2019-01-10 05:55

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

查看更多
趁早两清
7楼-- · 2019-01-10 05:55

A naive solution(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:]
查看更多
登录 后发表回答