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

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

当我测试这个时,它只存储/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.path.splitext()时自动发生的情况。在这个例子中:

components = os.path.splitext(filename)
prefix = components[0]
extension = components[1]
return os.path.join("avatars", instance.username, prefix, extension)

即使扩展名可能是。jpg,你最终会得到一个名为“foobar”的文件夹,而不是一个名为“foobar.jpg”的文件。为了防止这种情况,你需要单独追加扩展:

return os.path.join("avatars", instance.username, prefix) + extension

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

一刀就毁了它。

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

问题是你的笔记本电脑可能运行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。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)
os.path.join("a", *"/b".split(os.sep))
'a/b'

更完整的版本:

import os

def join (p, f, sep = os.sep):
    f = os.path.normpath(f)
    if p == "":
        return (f);
    else:
        p = os.path.normpath(p)
        return (os.path.join(p, *f.split(os.sep)))

def test (p, f, sep = os.sep):
    print("os.path.join({}, {}) => {}".format(p, f, os.path.join(p, f)))
    print("        join({}, {}) => {}".format(p, f, join(p, f, sep)))

if __name__ == "__main__":
    # /a/b/c for all
    test("\\a\\b", "\\c", "\\") # optionally pass in the sep you are using locally
    test("/a/b", "/c", "/")
    test("/a/b", "c")
    test("/a/b/", "c")
    test("", "/c")
    test("", "c")