mixed slashes with os.path.join on windows mixed slashes with os.path.join on windows windows windows

mixed slashes with os.path.join on windows


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

# .replace() all backslashes with forwardslashesprint 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.


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 osa = 'c:' # removed slashb = 'myFirstDirectory' # removed slashc = '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.


try using abspath (using python 3)

import osa = 'c:/'b = 'myFirstDirectory/'c = 'mySecondDirectory'd = 'myThirdDirectory'e = 'myExecutable.exe'print(os.path.abspath(os.path.join(a, b, c, d, e)))

OUTPUT:

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

Process finished with exit code 0