在Python中如何获取路径字符串中的“最后一个”目录?

问题描述 投票:0回答:1

我需要处理以下路径:

path1 = "/path/to/2012-01-01/files/2014-01-31/la.parquet"
path2 = "/path/to/2012-01-01/files/2014-01-31/"
path3 = "/path/to/2012-01-01/files/2014-01-31"

在所有情况下,最深的路径都是“2014-01-31”。有没有一种方法可以在一行代码中一致地获取此路径,或者我是否必须对文件名进行各种检查?

python path subdirectory
1个回答
0
投票

这可以使用pathlib来解决。这是一个简单的解决方案。

import pathlib


path1 = pathlib.Path("/path/to/2012-01-01/files/2014-01-31/la.parquet")
print(path1.parent.name)

参考

© www.soinside.com 2019 - 2024. All rights reserved.