Python os.path.join on Windows
Try this code:
mypath = os.path.join('c:%s' % os.sep, 'sourcedir')
You can use
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:
As @sharpcloud suggested, it would be better to remove the slashes from your input strings, however this is an alternative.
If for any reason you need to provide the paths yourself and you have using anything above python 3.4 you can use pathlib
from pathlib import Path, PurePosixPath a = PurePosixPath('c:/') b = PurePosixPath('myFirstDirectory/') c = 'mySecondDirectory' d = 'myThirdDirectory' e = 'myExecutable.exe' print(a / b / c / d / e) # Result c:/myFirstDirectory/mySecondDirectory/myThirdDirectory/myExecutable.exe
I used this when I needed a user to provide the location of an assets directory and my code was looking up using windows path strings
In : from pathlib import Path, PureWindowsPath In : USER_ASSETS_DIR = Path('/asset/dir') # user provides this form environment variable In : SPECIFIC_ASSET = PureWindowsPath('some\\asset') In : USER_ASSETS_DIR / SPECIFIC_ASSET Out: PosixPath('/asset/dir/some/asset')
You have a few possible approaches to treat path on Windows, from the most hardcoded ones (as using raw string literals or escaping backslashes) to the least ones. Here follows a few examples that will work as expected. Use what better fits your needs.
In: from os.path import join, isdir In: from os import sep In: isdir(join("c:", "\\", "Users")) Out: True In: isdir(join("c:", "/", "Users")) Out: True In: isdir(join("c:", sep, "Users")) Out: True