I have the path /bin/kk/bb/pp/hallo.png
and want to get: pp/hallo.png
. I checked https://docs.python.org/3/library/pathlib.html and found no direct way.
This is the way i use right now:
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
Output:
PosixPath('/pp/hallo.png')
I'm not happy with this and searching for a better / cleaner way.
Maybe something like this:
a[-2:] -> PosixPath('/pp/hallo.png')
You can do it like so:
from pathlib import Path
a = Path("/path/to/some/file.txt")
b = Path(*a.parts[-2:])
# PosixPath('some/file.txt')
Alternatively as a function:
def last_n_parts(filepath: Path, n: int = 2) -> Path:
return Path(*filepath.parts[-abs(n):])
The only reason I could think of that you'd need something like this is if you're specifying an output file that share the same directory structure. E.g. input is /bin/kk/bb/pp/hallo.png
and output will be /other/dir/pp/hallo.png
. In that case you can:
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')