[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Obtain the file's path.

On 17Sep2019 15:09, Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
>See the following two methods for obtaining the file's path:
>Which is more robust?

They're probably equally robust (BTW, you need the expanduser in the 
realpath call as well, if your filename might start with a tilde).

realpath will resolve symlinks and get you a path that does not pass 
through one. abspath is more lexical and just gets you a path which may 
traverse a symlink. Both return a valid absolute path (provided that 
file is an existing file).

My inclination is often to use abspath, because it may better express 
the "intent" of the filename by not "undoing" the effects of symlinks.

Consider the path "~/media/foo.mp4". In my home directory, "media" may 
be a symlink; on at least one machine it is a symlink into our larger 
RAID array.

So abspath(expanduser("~/media/foo.mp4")) might expand to 

Conversely, realpath(expanduser("~/media/foo.mp4")) might expand to 

If I rearrange things, for example by moving the media directory _and_ 
adjusting the ~/media symlink, then the old result of abspath will still 
work because it traverses the symlink "media". The old result of 
realpath will no longer be correct.

If you just want this for your running program's internals this may not 
matter, but if you're recording the result somewhere then abspath might 
get you a more "stable" path in the above scenario.

You might ask yourself, why do you need to know the absolute path at 
all? A relative path is usually just fine; it isn't like it won't work 
unless you use it from another directory.

Cameron Simpson <cs at cskk.id.au>