获取路径中的单个目录名称 Python 3.5

Getting individual Directory Names in a Path Python 3.5

假设我有这样的路径

Folder1/Folder2/Folder3/Folder4/

不一定要有最后的斜杠。 我如何提取 "Folder2".

使用标准库的'pathlib'模块:

>>> import pathlib
>>> pathlib.PurePath('Folder1/Folder2/Folder3/Folder4/').parts[1]

你得到:

'Folder2'

或子目录路径:

>>> pathlib.PurePath('Folder1/Folder2/Folder3/Folder4/').parents[1]

你得到:

PurePosixPath('Folder1/Folder2')