下面的代码不会加入,调试时该命令不存储整个路径,而只存储最后一个条目。
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
当我测试它时,它只存储代码的 /new_sandbox/
部分。
最佳答案
后面的字符串不应以斜杠开头。如果它们以斜线开头,则它们被视为“绝对路径”,并且它们之前的所有内容都将被丢弃。
引用 Python docs for os.path.join
:
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
注意在 Windows 上,与驱动器号相关的行为,与早期的 Python 版本相比似乎发生了变化:
On Windows, the drive letter is not reset when an absolute path component (e.g.,
r'\foo'
) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter is reset. Note that since there is a current directory for each drive,os.path.join("c:", "foo")
represents a path relative to the current directory on driveC:
(c:foo
), notc:\foo
.
关于python - 为什么 os.path.join() 在这种情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1945920/