Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to emulate os.path.samefile behaviour on Windows and Python 2.7?

Given two paths I have to compare if they're pointing to the same file or not. In Unix this can be done with os.path.samefile, but as documentation states it's not available in Windows. What's the best way to emulate this function? It doesn't need to emulate common case. In my case there are the following simplifications:

  • Paths don't contain symbolic links.
  • Files are in the same local disk.

Now I use the following:

def samefile(path1, path2)
    return os.path.normcase(os.path.normpath(path1)) == \
           os.path.normcase(os.path.normpath(path2))

Is this OK?

like image 804
Nikolay Polivanov Avatar asked Jan 17 '12 10:01

Nikolay Polivanov


1 Answers

I know this is a late answer in this thread. But I use python on Windows, and ran into this issue today, found this thread, and found that os.path.samefile doesn't work for me.

So, to answer the OP, now to emulate os.path.samefile, this is how I emulate it:

# because some versions of python do not have os.path.samefile
#   particularly, Windows. :(
#
def os_path_samefile(pathA, pathB):
  statA = os.stat(pathA) if os.path.isfile(pathA) else None
  if not statA:
    return False
  statB = os.stat(pathB) if os.path.isfile(pathB) else None
  if not statB:
    return False
  return (statA.st_dev == statB.st_dev) and (statA.st_ino == statB.st_ino)

It is not as tight as possible, because I was more interested in being clear in what I was doing.

I tested this on Windows-10, using python 2.7.15.

like image 57
Jesse Chisholm Avatar answered Oct 13 '22 16:10

Jesse Chisholm