Jagannath Ks Jagannath Ks - 3 months ago 27
Python Question

Comparing two paths in python

consider,

path1 = "c:/fold1/fold2"
list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]

if path1 in list_of_paths:
print "found"


I expect if statement to return true but it evaluates to False
since it is string comparision

how to compare two paths irrespective of forward or backward slash it has !
i dont prefer to use replace function and convert both string to comman format

Answer

Use os.path.normpath to convert c:/fold1/fold2 to c:\fold1\fold2:

>>> path1 = "c:/fold1/fold2"
>>> list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]
>>> os.path.normpath(path1)
'c:\\fold1\\fold2'
>>> os.path.normpath(path1) in list_of_paths
True
>>> os.path.normpath(path1) in (os.path.normpath(p) for p in list_of_paths)
True
  • os.path.normpath(path1) in map(os.path.normpath, list_of_paths) also works, but it will build a list with entire path items even though there's match in the middle. (In Python 2.x)
Comments