在Windows上与os.path.join混合斜杠 [英] mixed slashes with os.path.join on windows
问题描述
我倾向于仅对路径('/')使用正斜杠,而python在Windows上也很满意. 在os.path.join的描述中,它表示如果要跨平台使用,这是正确的方法.但是当我使用它时,我会得到混合的斜杠:
I tend to use only forward slashes for paths ('/') and python is happy with it also on windows. In the description of os.path.join it says that is the correct way if you want to go cross-platform. But when I use it I get mixed slashes:
import os
a = 'c:/'
b = 'myFirstDirectory/'
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'
print os.path.join(a, b, c, d, e)
# Result:
c:/myFirstDirectory/mySecondDirectory\myThirdDirectory\myExecutable.exe
这是正确的吗?我应该稍后检查并更正它,还是有更好的方法?
Is this correct? Should I check and correct it afterward or there is a better way?
谢谢
询问路径时,我还会得到斜杠
I also get mixed slashes when asking for paths
import sys
for item in sys.path:
print item
# Result:
C:\Program Files\Autodesk\Maya2013.5\bin
C:\Program Files\Autodesk\Maya2013.5\mentalray\scripts\AETemplates
C:\Program Files\Autodesk\Maya2013.5\Python
C:\Program Files\Autodesk\Maya2013.5\Python\lib\site-packages
C:\Program Files\Autodesk\Maya2013.5\bin\python26.zip\lib-tk
C:/Users/nookie/Documents/maya/2013.5-x64/prefs/scripts
C:/Users/nookie/Documents/maya/2013.5-x64/scripts
C:/Users/nookie/Documents/maya/scripts
C:\Program Files\Nuke7.0v4\lib\site-packages
C:\Program Files\Nuke7.0v4/plugins/modules
推荐答案
You are now providing some of the slashes yourself and letting os.path.join
pick others. It's better to let python pick all of them or provide them all yourself. Python uses backslashes for the latter part of the path, because backslashes are the default on Windows.
import os
a = 'c:' # removed slash
b = 'myFirstDirectory' # removed slash
c = 'mySecondDirectory'
d = 'myThirdDirectory'
e = 'myExecutable.exe'
print os.path.join(a + os.sep, b, c, d, e)
我还没有测试过,但是我希望这会有所帮助.具有基本路径并且只需要联接另一个元素(通常是文件)是更常见的.
I haven't tested this, but I hope this helps. It's more common to have a base path and only having to join one other element, mostly files.
顺便说一句;您可以在需要使用最佳分隔符的时刻使用 os.sep
操作系统python正在运行.
By the way; you can use os.sep
for those moments you want to have the best separator for the operating system python is running on.
如破折号所示,显然对于Windows,您确实需要为路径的根包括分隔符.否则,您将创建相对路径,而不是绝对路径.
as dash-tom-bang states, apparently for Windows you do need to include a separator for the root of the path. Otherwise you create a relative path instead of an absolute one.
这篇关于在Windows上与os.path.join混合斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!