Pathlib joining absolute path together

112 views Asked by At

I'm trying to join two path together, the second starts with a leading slash.

from pathlib  import Path

path = Path('/first', '/second')

# outputs WindowsPath('/second')
# expecting WindowsPath('/first/second')
print(path)

From the example above, you can see it removes the first path.

While it's not a big deal to use something like removeprefix('/'), I'm curious to know why it's behaving this way. Is there is a builtin way to change this behaviour?

1

There are 1 answers

0
The_Ball On

An absolute path is by definition fully qualified and it's not possible to add two absolute paths, which is why the behavior makes sense, the last absolute path overrides anything before it.

When dealing with virtual paths a convenience function like this is helpful:

def join_paths(*args: Path):
    """Concatenate paths even if some paths are absolute"""
    return Path(args[0], *[str(arg).lstrip('/') for arg in args[1:]])