2

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"

BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
Recessive
  • 1,780
  • 2
  • 14
  • 37
  • 2
    Since both paths start with `/`, they are by definition paths from the root - if you were to access one from the other or the other way around, you'd always get the absolute path from the root, so `os.join` is correct. Compare if `p1 = "/1/2"` and `p2 = "3/4"` – Grismar Jan 12 '22 at 00:38
  • @Grismar Ahh I see, I overlooked this because it's easy to forget a `/` somewhere in the code so I added a `/` to the start of the path for joining purposes, but this only made it worse! Thanks – Recessive Jan 12 '22 at 00:40

1 Answers1

3

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.

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257