下面的代码将不会连接,在调试时,命令不存储整个路径,而只存储最后一个条目。
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
当我测试这个时,它只存储/new_sandbox/部分的代码。
下面的代码将不会连接,在调试时,命令不存储整个路径,而只存储最后一个条目。
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
当我测试这个时,它只存储/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)
其他回答
问题是你的笔记本电脑可能运行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')
只使用new_sandbox试试
os.path.join('/home/build/test/sandboxes/', todaystr, 'new_sandbox')
这是因为'/new_sandbox/'以/开头,因此被认为是相对于根目录的。去掉前导的/。
Os.path.join()可以与os.path.sep一起使用来创建一个绝对路径,而不是相对路径。
os.path.join(os.path.sep, 'home','build','test','sandboxes',todaystr,'new_sandbox')