Obtain the file's path.

Pankaj Jangid pankaj.jangid at gmail.com
Wed Sep 18 04:42:43 EDT 2019


Cameron Simpson <cs at cskk.id.au> writes:

> 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?
>
> My inclination is often to use abspath, because it may better express
> the "intent" of the filename by not "undoing" the effects of symlinks.
>
> 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".
>
> 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.
>
Somewhat related to the OP's question.

So what is a good strategy in an application? I am now inclined to use
relative path and working directory both. And when there is change of
runtime context just change the working directory and assemble the
absolute path at runtime.

And to save the working directory use "abspath" as suggested by Cameron.

-- 
Pankaj Jangid



More information about the Python-list mailing list