How to test if two strings point to the same file or directory?

John Machin sjmachin at lexicon.net
Sat Dec 16 21:31:09 EST 2006


Tim Chase wrote:
> >>> Comparing file system paths as strings is very brittle. Is there a
> >>> better way to test if two paths point to the same file or directory
> >>> (and that will work across platforms?)
> >> 	os.path.samefile(filename1, filename2)
> >> 	os.path.sameopenfile(fileobject1, fileobject2)
> >
> > Nice try, but they don't "work across platforms".
>
> Okay...double-checking the docs.python.org writeup, it apparently
> does "work across platforms" (Mac & Unix), just not "across *all*
> platforms", with Win32 being the obvious outlier.

My bet would be that it really works on Unix only (OS/X qualifying as
Unix) and not on older Mac setups.

>  It seems a
> strange omission from Win32 python, even if it were filled in
> with only a stub...something like
>
> 	def samefile(f1, f2):
> 		return abspath(f1.lower()) == abspath(f2.lower())
>
> it might not so gracefully handle UNC-named files, or SUBST'ed
> file-paths, but at least it provides an attempt at providing the
> functionality on win32.  As it currently stands, it would be
> entirely too easy for a [Mac|*nix] programmer to see that there's
> a samefile() function available, use it successfully based on its
> docstring, only to have it throw an exception or silently fail
> when run on win32.

The current setup will not "silently fail when run on win32". How could
it? It doesn't exist; it can't be run.

Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit
(Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
| >>> import os
| >>> os.path.samefile
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'samefile'

The only way it could "silently fail when run on win32" would be to
have a "stub" which gave the wrong answer.




More information about the Python-list mailing list