Search code examples
pythonpathlib

How to compare cross-platform pathlib paths?


I would like to compare paths in my python unittests, sometimes on windows and sometimes on linux.

I am using pathlib, since it seems to be the way to go when using python 3.4 and newer.

import Path from pathlib

base_dir = Path('~/dev/test').expanduser() # String is given
wdir = base_dir.joinpath('examples/text') # Some other given path

print(wdir) 
# on Windows: WindowsPath(C:/Users/myUser/dev/test/examples/text)
# on Linux:   PosixPath(/home/myUser/dev/test/examples/text)

wdir seems to be totally different.

How to do a comparison that recognizes these two paths are semantically the same?

The differences are only because of the different platforms, is there a good way to compare paths across platforms (Windows, GNU/Linux)?


Solution

    • If the only difference is C:/Users and /home, you could do a comparison of .parts
    • If that doesn't work, there are a number of Methods and Properties, that might work.
    • The parts lists can be cast to sets, and then test a path for containment of the target path, using issubset.
    from pathlib import Path
    
    w = WindowsPath('C:/Users/myUser/dev/test/examples/text')
    l = PosixPath('/home/myUser/dev/test/examples/text')
    
    w.parts
    [out]:
    ('C:\\', 'Users', 'myUser', 'dev', 'test', 'examples', 'text')
    
    l.parts
    [out]:
    ('\\', 'home', 'myUser', 'dev', 'test', 'examples', 'text')
    
    # comparison
    l.parts[2:] == w.parts[2:]
    [out]:
    True
    
    # case issues can be resolved by mapping str.lower
    list(map(str.lower, w.parts))
    
    # use sets to determine if the target path is a subset of os_path
    def test_path(os_path: Path, target: Path):
        target = set(w.parts)
        os_path = set(map(str.lower(os_path.parts)))
        
        assert target.issubset(os_path)