Why would one use both, os.path.abspath and os.path.realpath?

前端 未结 3 1513
忘掉有多难
忘掉有多难 2020-12-02 06:21

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.

Howeve

3条回答
  •  悲哀的现实
    2020-12-02 07:03

    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.

提交回复
热议问题