如果尝试加入相同的文件夹名称,os.path.join() 将无法正常工作。如何解决?

os.path.join() does not work properly if try to join same folder names. How to fix it?

代码如下

import os

path_1 = "/folder/data"
path_2 = "/folder/media"

print(os.path.join(path_1, path_2))

输出结果如下

/folder/media

如何像这样正确地获得输出。

/folder/data/folder/media

我想要依赖于不同操作系统的程序的解决方案。因此添加变量 (path_1 + '/' + path_2) 不适合这个。

From the docs:

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

所以,您应该做的是删除第二个路径中的第一个斜杠:

import os

path_1 = "/folder/data"
path_2 = "folder/media"    # <- removed first slash

print(os.path.join(path_1, path_2))    # <- prints /folder/data/folder/media

就像另一个答案说的,你只需要把path_2改成path_2 = folder/media就可以了。您还可以使用 Pathlib 库来确保跨操作系统正确处理事情:

from pathlib import Path

path_1 = Path('/folder/data')
path_2 = Path('folder/data')

# extend the path to include path_2
path_2 = path_1 / path_2

print(path_2)