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 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.
EDIT based on comment: path = os.path.normpath(path)
My previous answer lacks the capability of handling escape characters and thus should not be used:
- First, convert the path to an array of folders and file name.
Second, glue them back together using the correct symbol.
import os path = 'c:\www\app\my/folder/file.php' # split the path to parts by either slash symbol: path = re.compile(r"[\/]").split(path) # join the path using the correct slash symbol: path = os.path.join(*path)
try using abspath (using python 3)
import os
a = '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
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.
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.