Windows 上的 python os.path.join 忽略第一个路径元素?
考虑以下内容:
>>> from django.conf import settings
>>> import os
>>> settings.VIRTUAL_ENV
'C:/Users/Marcin/Documents/oneclickcos'
>>> settings.EXTRA_BASE
'/oneclickcos/'
>>> os.path.join(settings.VIRTUAL_ENV,settings.EXTRA_BASE)
'/oneclickcos/'
正如您可以想象的那样,我既不期望也不希望将 'C:/Users/Marcin/Documents/oneclickcos'
和 '/oneclickcos/'
连接起来为'/oneclickcos/'
。
奇怪的是,反转路径组件再次显示 python 忽略第一个路径组件:
>>> os.path.join(settings.EXTRA_BASE,settings.VIRTUAL_ENV)
'C:/Users/Marcin/Documents/oneclickcos'
虽然这工作起来与预期类似:
>>> os.path.join('/foobar',settings.VIRTUAL_ENV,'barfoo')
'C:/Users/Marcin/Documents/oneclickcos\\barfoo'
我当然是在 Windows (Windows 7) 上运行,使用本机 python。
为什么会发生这种情况,我该怎么办?
Consider the following:
>>> from django.conf import settings
>>> import os
>>> settings.VIRTUAL_ENV
'C:/Users/Marcin/Documents/oneclickcos'
>>> settings.EXTRA_BASE
'/oneclickcos/'
>>> os.path.join(settings.VIRTUAL_ENV,settings.EXTRA_BASE)
'/oneclickcos/'
As you can imagine, I neither expect nor want the concatenation of 'C:/Users/Marcin/Documents/oneclickcos'
and '/oneclickcos/'
to be '/oneclickcos/'
.
Oddly enough, reversing the path components once again shows python ignoring the first path component:
>>> os.path.join(settings.EXTRA_BASE,settings.VIRTUAL_ENV)
'C:/Users/Marcin/Documents/oneclickcos'
While this works something like expected:
>>> os.path.join('/foobar',settings.VIRTUAL_ENV,'barfoo')
'C:/Users/Marcin/Documents/oneclickcos\\barfoo'
I am of course, running on Windows (Windows 7), with the native python.
Why is this happening, and what can I do about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这几乎就是 os.path.join 的定义方式(引用 文档):
,我想说这通常是一件好事,因为它避免创建无效路径。如果您想避免这种行为,请不要为其提供绝对路径。是的,以斜线开头的就是绝对路径。一个快速而肮脏的解决方案就是删除前导斜杠(如果您想以编程方式执行此操作,则为
settings.EXTRA_BASE.lstrip('/')
)。That's pretty much how
os.path.join
is defined (quoting the docs):And I'd say it's usually a good thing, as it avoids creating invalid paths. If you want to avoid this behavior, don't feed it absolute paths. Yes, starting with a slash qualifies as absolute path. A quick and dirty solution is just removing the leading slash (
settings.EXTRA_BASE.lstrip('/')
if you want to do it programmatically).从第二个字符串中删除前导
/
:这是因为
os.path.join
一旦遇到绝对路径就会丢弃所有先前的组件,而/oneclickos/< /code> 是绝对路径。
以下是 os.path.join 文档的摘录:
Remove the leading
/
from the second string:This is because
os.path.join
discards all previous components once it meets an absolute path, and/oneclickos/
is an absolute path.Here's an excerpt from the doc of
os.path.join
: