mixed slashes with os.path.join on windows

前端 未结 7 1444
一生所求
一生所求 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 05:00

    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')
    

提交回复
热议问题