mixed slashes with os.path.join on windows

前端 未结 7 1448
一生所求
一生所求 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:45

    os adds slashes for you and makes sure not to duplicate slashes so omit them in your strings

    import os
    
    # Don't add your own slashes
    a = 'C:'
    b = 'myFirstDirectory' 
    c = 'mySecondDirectory'
    d = 'myThirdDirectory'
    e = 'myExecutable.exe'
    
    print os.path.join(a, b, c, d, e)
    C:\myFirstDirectory\mySecondDirectory\myThirdDirectory\myExecutable.exe
    

    Additional:

    I'm unsure as to why you have mixed slashes in your sys path (have you used a linux os to add some folders?) but try checking

    print os.path.isdir(os.path.join('C:','Users','nookie')).

    If this is True then os works for your mixed slashes.

    Either way, I would avoid hard-coding directory names into your program. Your sys.path for loop is a safe way to pull out these directories. You can then use some string methods, or regex to pick the desired folder.

提交回复
热议问题