Comparing two paths in python



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.

Asked By: Jagannath Ks



Store the list_of_paths as a list instead of a string:

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

Then split given path by ‘/’ or ” (whichever is present) and then use the in keyword.

Answered By: Aswin Murugesh

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

>>> path1 = "c:/fold1/fold2"
>>> list_of_paths = ["c:\fold1\fold2","c:\temp\temp123"]
>>> os.path.normpath(path1)
>>> os.path.normpath(path1) in list_of_paths
>>> os.path.normpath(path1) in (os.path.normpath(p) for p in list_of_paths)
  • 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)

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

Answered By: falsetru

Use os.path.normpath to canonicalize the paths before comparing them. For example:

if any(os.path.normpath(path1) == os.path.normpath(p)
       for p in list_of_paths):
    print "found"
Answered By: user4815162342

The os.path module contains several functions to normalize file paths so that equivalent paths normalize to the same string. You may want normpath, normcase, abspath, samefile, or some other tool.

Answered By: user2357112

All of these answers mention os.path.normpath, but none of them mention os.path.realpath:


Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).

New in version 2.2.

So then:

if os.path.realpath(path1) in (os.path.realpath(p) for p in list_of_paths):
    # ...
Answered By: Jonathon Reinhart

If you are using , you can use to achieve your goal:

import pathlib
path1 = pathlib.Path("c:/fold1/fold2")
list_of_paths = [pathlib.Path(path) for path in ["c:\fold1\fold2","c:\temp\temp123"]]
assert path1 in list_of_paths
Answered By: pkowalczyk
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.