Search code examples
pythonpathlib

Pathlib with backlashes within input string


I tried to check if a given path exists on Windows/Linux (using Path.exists())

A FileNotFoundError is raised on Linux only, obviously when looking at the POSIX path object it is not converted to POSIX.

I would like to know why pathlib does not convert the Windows-style path to a POSIX path (currently running on Windows):

from pathlib import PosixPath, WindowsPath, Path, PurePosixPath, PureWindowsPath
raw_string = r'.\mydir\myfile'
print(Path(raw_string))
print(PurePosixPath(raw_string))

Output:

.\mydir\myfile
.\mydir\myfile

Both Windows and Linux pathlib path imports of the raw_string show the same Windows path as the output, and such a Windows path is of course not usable on Linux (second output).

Shouldn't pathlib take care of these conversions for Path objects to be platform-agnostic?

So that the last output should look like:

./mydir/myfile

Solution

  • Found a solution: Path(PureWindowsPath(raw_string)) works on either platform. It’s useful if you’re developing on Windows and want to simply copy paste long Windows formatted file paths.

    raw_string = r'.\mydir\myfile'
    print(Path(PureWindowsPath(raw_string)))
    

    Output:

    mydir/myfile
    

    And you need the PureWindowsPath. If on a Linux system, you just code print(Path(WindowsPath(raw_string))) instead, you will get the error:

    NotImplementedError: cannot instantiate 'WindowsPath' on your system