首页 > 解决方案 > 使用 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')

标签: pythonpathpathlib

解决方案


你可以这样做:

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

推荐阅读