mixed slashes with os.path.join on windows

前端 未结 7 1422
一生所求
一生所求 2020-11-27 04:39

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 w

7条回答
  •  一向
    一向 (楼主)
    2020-11-27 04:59

    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.

提交回复
热议问题