Question
Asked By – hch
In multiple open source projects, I have seen people do os.path.abspath(os.path.realpath(__file__))
to get the absolute path to the current file.
However, I find that os.path.abspath(__file__)
and os.path.realpath(__file__)
produce the same result. os.path.abspath(os.path.realpath(__file__))
seems to be a bit redundant.
Is there a reason people are using that?
Now we will see solution for issue: Why would one use both, os.path.abspath and os.path.realpath?
Answer
os.path.realpath
derefences symbolic links on those operating systems which support them.
os.path.abspath
simply removes things like .
and ..
from the path giving a full path from the root of the directory tree to the named file (or symlink)
For example, on Ubuntu
$ ls -l
total 0
-rw-rw-r-- 1 guest guest 0 Jun 16 08:36 a
lrwxrwxrwx 1 guest guest 1 Jun 16 08:36 b -> a
$ python
Python 2.7.11 (default, Dec 15 2015, 16:46:19)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from os.path import abspath, realpath
>>> abspath('b')
'/home/guest/play/paths/b'
>>> realpath('b')
'/home/guest/play/paths/a'
Symlinks can contain relative paths, hence the need to use both. The inner call to realpath
might return a path with embedded ..
parts, which abspath
then removes.
This question is answered By – kdopen
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0