Python os.path.join on Windows

Python os.path.join on Windows

Asked on October 26, 2018 in Windows.
Add Comment


  • 7 Answer(s)

    Use this code:

    "c:/sourcedir"
    
    os.path.join("/", "c:", "sourcedir")
    
    os.path.join("c:/", "sourcedir")
    
    
    Answered on October 26, 2018.
    Add Comment

       Use this code  to solve the Python os.path.join on Windows:

    mypath = os.path.join('c:', os.sep, 'sourcedir')
    

       Since we need os.sep for the posix root path:

    mypath = os.path.join(os.sep, 'usr', 'lib')
    
    Answered on October 26, 2018.
    Add Comment

    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.

    Answered on January 19, 2019.
    Add Comment

    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 [1]: from pathlib import Path, PureWindowsPath
    In [2]: USER_ASSETS_DIR = Path('/asset/dir') # user provides this form environment variable
    In [3]: SPECIFIC_ASSET = PureWindowsPath('some\\asset')
    In [4]: USER_ASSETS_DIR / SPECIFIC_ASSET
    
    Out[4]: PosixPath('/asset/dir/some/asset')
    Answered on January 19, 2019.
    Add Comment
    2

    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[1]: from os.path import join, isdir
    
    In[2]: from os import sep
    
    In[3]: isdir(join("c:", "\\", "Users"))
    Out[3]: True
    
    In[4]: isdir(join("c:", "/", "Users"))
    Out[4]: True
    
    In[5]: isdir(join("c:", sep, "Users"))
    Out[5]: True

     

    Answered on January 30, 2019.
    Add Comment
    sys.path.append('{0}'.join(os.path.dirname(__file__).split(os.path.sep)[0:-1]).format(os.path.sep))
    Answered on February 17, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.