Obtain the file's path.

Cameron Simpson cs at cskk.id.au
Wed Sep 18 00:13:43 EDT 2019


On 17Sep2019 15:09, Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
>See the following two methods for obtaining the file's path:
>
>os.path.realpath(file)
>or
>os.path.abspath(os.path.expanduser(file))
>
>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 
"/home/cameron/media/foo.mp4".

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

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.

Cheers,
Cameron Simpson <cs at cskk.id.au>



More information about the Python-list mailing list