Search code examples
pythonbackslashslash

'/' or '\' for paths?


I am having this problem when sharing files with my friends...

I have windows, some use mac and others Linux. When I share python files that contain commands of creating directories, like for instance:

Path_Results = os.path.dirname(Path_Definition)+'\Results'

the directory is not created because in Windows \ is used, whereas in mac and linux / are used. Any ideas how can I create a more general script ?

Thanks in advance


Solution

  • Use pathlib.Path. Then you'll stop concerning yourself with / or \

    On Windows:

    >>> from pathlib import Path
    >>> updir = Path("..")
    >>> resdir = updir / "Result"
    >>> resdir
    WindowsPath('../Result')
    >>> str(resdir)
    '..\\Result'
    

    On Linux, Mac, BSD, and other *nix:

    >>> from pathlib import Path
    >>> updir = Path("..")
    >>> resdir = updir / "Result"
    >>> resdir
    PosixPath('../Result')
    >>> str(resdir)
    '../Result'
    

    Nearly all stdlib modules and functions accept Path as is, no need to str() it. Example:

    from pathlib import Path
    resdir = Path("../Result")
    filepath = resdir / "somefilename.txt"
    assert isinstance(filepath, Path)
    with open(filepath, "rt") as fin:
        for ln in fin:
            # do things
    

    Provided there's a file ..\Result\somefilename.txt (in Windows) or ../Result/somefilename.txt (in Linux/Mac/BSD), the code will work exactly the same.


    Edit: For your particular code:

    from pathlib import Path
    
    ...
    
    # Assuming `Path_Definition` is not a Path object
    Path_Results = Path(Path_Definition) / 'Results'