在python中,假设我有一个这样的路径:
/folderA/folderB/folderC/folderD/
我怎样才能得到folderD部分?
在python中,假设我有一个这样的路径:
/folderA/folderB/folderC/folderD/
我怎样才能得到folderD部分?
当前回答
如果你使用本地python包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.name
'file.txt'
>>> your_path.parent
'folderD'
其他回答
我喜欢Path的部分方法:
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}')
path = "/folderA/folderB/folderC/folderD/"
last = path.split('/').pop()
str = "/folderA/folderB/folderC/folderD/"
print str.split("/")[-2]
以下是我的方法:
>>> 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
我正在寻找一个解决方案,以获得文件所在的最后一个文件夹名,我只是使用分裂两次,以获得正确的部分。这不是问题,但谷歌把我调到了这里。
pathname = "/folderA/folderB/folderC/folderD/filename.py"
head, tail = os.path.split(os.path.split(pathname)[0])
print(head + " " + tail)