Python os.path.join incorrectly appending paths

Viewed 152

The python os module seems to be incorrectly joining paths. To replicate, simply run the following code:

import os
p1 = "/1/2"
p2 = "/3/4"
print(os.path.join(p1,p2))

Which will print "/3/4". Is this the expected behaviour? I would expect it to print "/1/2/3/4"

1 Answers

That is by design:

If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

If 3/4 should be a subdirectory of /1/2, omit the leading /:

import os

p1 = "/1/2"
p2 = "3/4"
print(os.path.join(p1,p2))

As Olvin Roght suggests, you can also remove leading slashes from p2 using something like this:

p2 = p2.lstrip("/\\")

before trying to join if you cannot directly modify the string. This will remove / or \ characters from the string.

Related