Python os.path.join 错误地附加路径

Python os.path.join incorrectly appending paths

python os 模块似乎错误地加入了路径。要复制,只需 运行 以下代码:

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

这将打印 "/3/4"。这是预期的行为吗?我希望它打印 "/1/2/3/4"

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.

如果 3/4 应该是 /1/2 的子目录,则省略前导 /:

import os

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

作为 ,您还可以使用如下方式从 p2 中删除前导斜线:

p2 = p2.lstrip("/\")

如果您不能直接修改字符串,请在尝试加入之前。这将从字符串中删除 /\ 个字符。