user3654650
user3654650

Reputation: 6103

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?

Upvotes: 7

Views: 7926

Answers (2)

kuropan
kuropan

Reputation: 896

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

Upvotes: 6

Marcin
Marcin

Reputation: 238101

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.

Upvotes: 15

Related Questions