python - 使用 pathlib 获取文件名和最后 x 个目录名称是否有更好的方法
问题描述
我有路径/bin/kk/bb/pp/hallo.png
,想得到:pp/hallo.png
。我检查了https://docs.python.org/3/library/pathlib.html 并没有找到直接的方法。
这是我现在使用的方式:
from pathlib import Path
a = Path("/bin/kk/bb/pp/hallo.png")
# get the parts i want
b = list(a.parts[-2:])
# add / and join all together
c = "".join([ "/" + x for x in b])
d = Path(c)
d
输出:
PosixPath('/pp/hallo.png')
我对此不满意并寻找更好/更清洁的方式。
也许是这样的:
a[-2:] -> PosixPath('/pp/hallo.png')
解决方案
你可以这样做:
from pathlib import Path
a = Path("/path/to/some/file.txt")
b = Path(*a.parts[-2:])
# PosixPath('some/file.txt')
或者作为一个函数:
def last_n_parts(filepath: Path, n: int = 2) -> Path:
return Path(*filepath.parts[-abs(n):])
我能想到你需要这样的东西的唯一原因是如果你指定一个共享相同目录结构的输出文件。例如输入是/bin/kk/bb/pp/hallo.png
,输出是/other/dir/pp/hallo.png
。在这种情况下,您可以:
in_file = Path("/bin/kk/bb/pp/hallo.png")
out_dir = Path("/other/dir")
out_file = out_dir / last_n_parts(in_file)
# PosixPath('/other/dir/pp/hallo.png')
推荐阅读
- r - 根据一个表的列名和另一个表的列值合并两个大data.tables而不熔化
- testing - 当被测试的服务器放弃时,Jmeter 测试总是冻结
- django - Django中的用户创建表单
- android - 从适配器更新 Activity 中的 EditText
- angular - Angular SEO 元标记“http-equiv”和“httpequiv”是一样的吗?
- php - Apache config:有没有办法在所有虚拟主机上使用“php-fpm”,除了两个目录?
- python - 如何在 Python 中将列表的各个元素链接到一个单独的元素中
- php - 我正在使用 laravel 框架。它说这条路线不支持 POST 方法。支持的方法:GET、HEAD
- java - 从 XML 布局生成时仅显示 1 页的 PDF
- eloquent - SoftDelete 恢复特定用户