python - 为什么 os.path.join() 在这种情况下不起作用?

标签 python path

下面的代码不会加入,调试时该命令不存储整个路径,而只存储最后一个条目。

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 drive C: (c:foo), not c:\foo.

关于python - 为什么 os.path.join() 在这种情况下不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1945920/

相关文章:

ruby-on-rails - 如何获取rails中的当前 View 路径?

html - 没有文件正在使用 ../返回文件

c# - 我如何在 C# 中解决 Web/Windows 应用程序中的相对路径

python - 在 BeautifulSoup 标签上使用正则表达式

python - 使用django上传图片

将整数转换为二进制的Python代码

python - 如何使用 ci.yml 声明要在 python 中使用的环境变量?

python - opencv2 中阈值 32 uint 图像的轮廓和凸包

node.js - npm 安装后找不到 Docker 镜像错误 bin

windows - 递归路径