mixed slashes with os.path.join on windows

nookie picture nookie · May 2, 2013 · Viewed 84.6k times · Source

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?

Thanks

EDIT: 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

Answer

Maximus picture Maximus · Sep 13, 2013

You can use .replace() after path.join() to ensure the slashes are correct:

# .replace() all backslashes with forwardslashes
print os.path.join(a, b, c, d, e).replace("\\","/")

This gives the output:

c:/myFirstDirectory/mySecondDirectory/myThirdDirectory/myExecutable.exe

As @sharpcloud suggested, it would be better to remove the slashes from your input strings, however this is an alternative.