6

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?

user3654650
  • 5,283
  • 10
  • 27
  • 28

2 Answers2

13

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.

Marcin
  • 215,873
  • 14
  • 235
  • 294
6

For anyone using a newer python version than OP: Starting with python 3.5, you can also use path1.samefile(path2), see documentation.

kuropan
  • 774
  • 7
  • 18