Chonghao  Huang Chonghao Huang - 1 month ago 10
Python Question

why use both os.path.abspath and os.path.realpath

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?

Answer

os.path.realpath derefences symbolic links on those operating systems which support them.

os.path.abspath simply removes things like '~' (Home directory), '.' 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.