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

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

当我测试这个时,它只存储/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.join()的思想是让你的程序跨平台(linux/windows/etc)。

一刀就毁了它。

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

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

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

对于已有连接的字符串,尝试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', "]

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

你可以去掉'/':

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