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

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

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


当前回答

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

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

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

其他回答

为了帮助理解为什么这种令人惊讶的行为并不完全可怕,考虑一个接受配置文件名作为参数的应用程序:

config_root = "/etc/myapp.conf/"
file_name = os.path.join(config_root, sys.argv[1])

如果应用程序以以下方式执行:

$ myapp foo.conf

将使用配置文件/etc/myapp.conf/foo.conf。

但是考虑一下如果应用程序被调用时会发生什么:

$ myapp /some/path/bar.conf

然后myapp应该使用/some/path/bar.conf的配置文件(而不是/etc/myapp.conf/some/path/bar.conf或类似文件)。

这可能不是很好,但我相信这是绝对路径行为的动机。

只使用new_sandbox试试

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

Os.path.join()可以与os.path.sep一起使用来创建一个绝对路径,而不是相对路径。

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

为了让你的函数更可移植,可以这样使用它:

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

or

os.path.join(os.environ.get("HOME"), 'test', 'sandboxes', todaystr, 'new_sandbox')

我建议从第二个和下面的字符串中剥离字符串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)