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

Sandra-24 sandravandale at yahoo.com
Sat Dec 16 21:26:12 EST 2006


On Dec 16, 8:30 pm, Steven D'Aprano
<s... at REMOVE.THIS.cybersource.com.au> wrote:
> On Sat, 16 Dec 2006 17:02:04 -0800, Sandra-24 wrote:
> > Comparing file system paths as strings is very brittle.Why do you say that? Are you thinking of something like this?
>
> /home//user/somedirectory/../file
> /home/user/file
>
> Both point to the same file.
>
> > Is there a
> > better way to test if two paths point to the same file or directory
> > (and that will work across platforms?)How complicated do you want to get? If you are thinking about aliases,
> hard links, shortcuts, SMB shares and other complications, I'd be
> surprised if there is a simple way.

So would I. Maybe it would make a good addition to the os.path library?

os.path.isalias(path1, path2)

> But for the simple case above:
>
> >>> import os
> >>> path = '/home//user/somedirectory/../file'
> >>> os.path.normpath(path)'/home/user/file'

The simplest I can think of that works for me is:

def isalias(path1, path2):
...     return os.path.normcase(os.path.normpath(path1)) ==
os.path.normcase(os.path.normpath(path2))

But that won't work with more complicated examples. A common one that
bites me on windows is shortening of path segments to 6 characters and
a ~1.

-Dan




More information about the Python-list mailing list