pythonpython-2.7path

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 would like the if statement to return True, but it evaluates to False, since it is a string comparison.

How to compare two paths irrespective of the forward or backward slashes they have? I'd prefer not to use the replace function to convert both strings to a common format.


Solution

  • 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
    

    On Windows, you must use os.path.normcase to compare paths because on Windows, paths are not case-sensitive.