Chonghao  Huang Chonghao Huang - 9 months ago 81
Python Question

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

In multiple open source projects, I have seen people do

to get the absolute path to the current file. However, I find that
produce the same result.
seems to be a bit redundant. Is there a reason people are using that?

Answer Source

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')
>>> realpath('b')

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.