Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 520
Jagannath Ks Avatar asked Jan 16 '14 10:01

Jagannath Ks


People also ask

How do you compare two paths in Python?

path. samefile() method in Python is used to check whether the given two pathnames refer to the same file or directory or not. This is determined by comparing device number and i-node number of the given paths.


4 Answers

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)

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

like image 86
falsetru Avatar answered Sep 20 '22 13:09

falsetru


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

os.path.realpath(path)

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):     # ... 
like image 33
Jonathon Reinhart Avatar answered Sep 20 '22 13:09

Jonathon Reinhart


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.

like image 20
user2357112 supports Monica Avatar answered Sep 21 '22 13:09

user2357112 supports Monica


If you are using python-3, you can use pathlib 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
like image 38
pkowalczyk Avatar answered Sep 20 '22 13:09

pkowalczyk