下面的代码将不会连接,在调试时,命令不存储整个路径,而只存储最后一个条目。

os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')

当我测试这个时,它只存储/new_sandbox/部分的代码。


当前回答

os.path.join()的思想是让你的程序跨平台(linux/windows/etc)。

一刀就毁了它。

所以它只有在与某种参考点一起使用时才有意义 操作系统。environ['HOME']或os.path.dirname(__file__)。

其他回答

我建议从第二个和下面的字符串中剥离字符串os.path。Sep,防止它们被解释为绝对路径:

first_path_str = '/home/build/test/sandboxes/'
original_other_path_to_append_ls = [todaystr, '/new_sandbox/']
other_path_to_append_ls = [
    i_path.strip(os.path.sep) for i_path in original_other_path_to_append_ls
]
output_path = os.path.join(first_path_str, *other_path_to_append_ls)

像这样,去掉多余的斜杠

root="/home"
os.path.join(root,"build","test","sandboxes",todaystr,"new_sandbox")

后面的字符串不应该以斜杠开头。如果它们以斜杠开头,那么它们被认为是“绝对路径”,之前的所有内容都将被丢弃。

引用Python文档中的os.path.join:

如果一个组件是一个绝对路径,那么之前的所有组件都将被丢弃,连接将继续从绝对路径组件开始。

注意,在Windows上,与驱动器号相关的行为,与早期的Python版本相比,似乎已经发生了变化:

在Windows上,当遇到绝对路径组件(例如r'\foo')时,驱动器号不会重置。如果组件中包含驱动器号,则丢弃之前的所有组件并重置驱动器号。注意,由于每个驱动器都有一个当前目录,os.path。join("c:", "foo")表示相对于c盘(c:foo)上当前目录的路径,而不是c:\foo。

你可以去掉'/':

>>> os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/'.strip('/'))
'/home/build/test/sandboxes/04122019/new_sandbox'

不要在路径组件的开头使用正斜杠,除非指向根目录:

os.path.join('/home/build/test/sandboxes', todaystr, 'new_sandbox')

参见:http://docs.python.org/library/os.path.html#os.path.join