Search code examples
pythonwindowsposixpathlib

Convert WindowsPath to PosixPath


I am using pathlib to manage my paths in my Python project using the Path class.

When I am using Linux, everything works fine. But on Windows, I have a little issue.

At some point in my code, I have to write a JavaScript file which lists the references to several other files. These paths have to be written in POSIX format. But when I do str(my_path_instance) on Windows, The path is written in Windows format.

Do you know a simple way to convert a WindowsPath to a PosixPath with pathlib?


Solution

  • pathlib has an as_posix method to convert from Windows to POSIX paths:

    pathlib.path(r'foo\bar').as_posix()
    

    Apart from this, you can generally construct system-specific paths by calling the appropriate constructor. The documentation states that

    You cannot instantiate a WindowsPath when running on Unix, but you can instantiate PureWindowsPath. [or vice versa]

    So use the Pure* class constructor:

    str(pathlib.PurePosixPath(your_posix_path))
    

    However, this won’t do what you want if your_posix_path contains backslashes, since \ (= Windows path separator) is just a regular character as far as POSIX is concerned. So a\b is valid POSIX filename, not a path denoting a file b inside a directory b, and PurePosixPath will preserve this interpretation:

    >>> str(pathlib.PurePosixPath(r'a\b'))
    'a\\b'
    

    To convert Windows to POSIX paths, use the PureWindowsPath class and convert via as_posix:

    >>> pathlib.PureWindowsPath(r'a\b').as_posix()
    'a/b'