有没有更好的方法通过使用 pathlib 获取文件名和最后一个 x 目录名
Is ther a better way of getting the file name and the last x diretory names by using pathlib
我有路径 /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')
我有路径 /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')