Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you prefix a Python pathlib.Path with another path?

I have a pathlib.Path('/etc'). If I need to prefix it with pathlib.Path('/mnt/chroot') and do something like:

Path('/mnt/chroot') / Path('/etc')

I just end up with: PosixPath('/etc'), presumably because both Path's are absolute paths, and can't be concatenated.

I can hack together a solution with something like:

Path('/mnt/chroot') / str(Path('/etc')).removeprefix('/')

But that is long-winded, and hackish. Is there a simpler, proper way to do this?

like image 621
John Avatar asked Mar 09 '26 10:03

John


2 Answers

You can turn Path('/etc') into a relative path with the relative_to method:

Path('/mnt/chroot') / Path('/etc').relative_to('/')
like image 62
Kyle Parsons Avatar answered Mar 12 '26 08:03

Kyle Parsons


I just want to expand on Kyle's answer with a cross platform solution. It dynamically gets the root of the filesystem.

root = os.path.abspath(".").split(os.path.sep)[0] + os.path.sep
path = Path("/mnt/chroot") / Path("/etc").relative_to(root)

Do not know if this adds anything but here it is.

like image 39
Quber Avatar answered Mar 12 '26 08:03

Quber