Search code examples
pythonpython-3.xpathpathlib

In Python 3.4, what is best/easiest way to compare paths?


Using this code in Python 3.4 and Ubuntu 14.04 do not return True

import pathlib

path1 = pathlib.Path("/tmp")
path2 = pathlib.Path("/tmp/../tmp")

print(path1 == path2)
# gives False

print(path1 is path2)
# gives False

But normally "/tmp" and "/tmp/../tmp" are the same folder. So how to ensure that the comparisons return True?


Solution

  • To compare you should resolve the paths first or you can also use os.path.samefile. Example:

    print(path1.resolve() == path2.resolve())
    # True       
    
    import os
    print(os.path.samefile(str(path1), str(path2)))
    # True
    

    By the way, path1 is path2 checkes if path1 is the same object as path2 rather than comparing actual paths.