为什么os.path.join()在这种情况下不起作用? [英] Why doesn't os.path.join() work in this case?
问题描述
下面的代码将不会加入,调试后,该命令将不会存储整个路径,而只会存储最后一个条目.
The below code will not join, when debugged the command does not store the whole path but just the last entry.
os.path.join('/home/build/test/sandboxes/', todaystr, '/new_sandbox/')
当我对此进行测试时,它仅存储代码的/new_sandbox/
部分.
When I test this it only stores the /new_sandbox/
part of the code.
推荐答案
后面的字符串不应以斜杠开头.如果它们以斜杠开头,则它们被认为是绝对路径",并且之前的所有内容都将被丢弃.
The latter strings shouldn't start with a slash. If they start with a slash, then they're considered an "absolute path" and everything before them is discarded.
引用 os.path.join
的Python文档:
Quoting the 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版本相比似乎有所改变:
Note on Windows, the behaviour in relation to drive letters, which seems to have changed compared to earlier Python versions:
在Windows上,当遇到绝对路径成分(例如,
r'\foo'
)时,不会重置驱动器号.如果组件包含驱动器号,则会丢弃所有先前的组件,并重置驱动器号.请注意,由于每个驱动器都有一个当前目录,因此os.path.join("c:", "foo")
表示相对于驱动器C:
(c:foo
)上当前目录的路径,而不是c:\foo
.
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
.
这篇关于为什么os.path.join()在这种情况下不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!