nookie nookie - 6 months ago 49
Python Question

mixed slashes with os.path.join on windows

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:

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\\lib-tk
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 do 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.

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.

Edit: 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.