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

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

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


当前回答

对于已有连接的字符串,尝试split("/")和*的组合。

import os

home = '/home/build/test/sandboxes/'
todaystr = '042118'
new = '/new_sandbox/'

os.path.join(*home.split("/"), todaystr, *new.split("/"))

它是如何工作的…

Split("/")将现有路径转换为列表:[",'home', 'build', 'test', 'sandboxes', "]

*在列表前面列出列表的每一项自己的参数

其他回答

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

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或类似文件)。

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

你可以去掉'/':

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

问题是你的笔记本电脑可能运行windows。Window烦人地使用后斜杠而不是前斜杠'/'。让你的程序跨平台(linux/windows/etc)。 如果想要os.path.join正确地处理它们,就不应该在路径中提供任何斜杠(向前或向后)。你应该使用:

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

或者抛出一些Path(__file__).resolve()。Parent(当前文件的父路径)或任何东西,这样你就不会在os.path.join中使用任何斜杠

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

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')

像这样,去掉多余的斜杠

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