os.path.join 似乎对开头的斜线很敏感,为什么?
os.path.join seems sensitive to opening slash, why?
在 os.join 中向文档添加斜线会产生不同的结果,但我认为不应该这样做。为什么?
只是尝试编写为多个用户做合理事情的代码。
import os
# Initialize output files and folders, following principle of separating code from data
homeDir = os.path.expanduser('~')
targetDir = os.path.join(homeDir, '/Documents/Jeopardy/output')
print(targetDir)
# produces /Documents/Jeopardy/output which is not expected
targetDir = os.path.join(homeDir, 'Documents/Jeopardy/output')
print(targetDir)
# produces /home/max/Documents/Jeopardy/output which is expected
我希望两个连接都能产生
/home/max/Documents/Jeopardy/output
但是第一个没有。我一定不明白加入文档,但我不明白为什么我会得到不同的输出。
提前致谢
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
'/Documents/Jeopardy/output'
是绝对路径,所以第一部分被舍弃。
从行为上讲,使用相对路径而不是绝对路径可以说更有意义;将任何内容添加到绝对路径之前没有多大意义,因为它已经从 FS 根目录开始。
在 os.join 中向文档添加斜线会产生不同的结果,但我认为不应该这样做。为什么?
只是尝试编写为多个用户做合理事情的代码。
import os
# Initialize output files and folders, following principle of separating code from data
homeDir = os.path.expanduser('~')
targetDir = os.path.join(homeDir, '/Documents/Jeopardy/output')
print(targetDir)
# produces /Documents/Jeopardy/output which is not expected
targetDir = os.path.join(homeDir, 'Documents/Jeopardy/output')
print(targetDir)
# produces /home/max/Documents/Jeopardy/output which is expected
我希望两个连接都能产生 /home/max/Documents/Jeopardy/output 但是第一个没有。我一定不明白加入文档,但我不明白为什么我会得到不同的输出。 提前致谢
If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.
'/Documents/Jeopardy/output'
是绝对路径,所以第一部分被舍弃。
从行为上讲,使用相对路径而不是绝对路径可以说更有意义;将任何内容添加到绝对路径之前没有多大意义,因为它已经从 FS 根目录开始。