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

前端 未结 3 1489
忘掉有多难
忘掉有多难 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:11

    For your stated scenario, there is no reason to combine realpath and abspath, since os.path.realpath actually calls os.path.abspath before returning a result (I checked Python 2.5 to Python 3.6).

    • os.path.abspath returns the absolute path, but does NOT resolve symlinks in its argument.
    • os.path.realpath will first resolve any symbolic links in the path, and then return the absolute path.

    However, if you expect your path to contain a ~, neither abspath or realpath will resolve ~ to the user's home directory, and the resulting path will be invalid. You will need to use os.path.expanduser to resolve this to the user's directory.

    For the sake of a thorough explanation, here are some results which I've verified in Windows and Linux, in Python 3.4 and Python 2.6. The current directory (./) is my home directory, which looks like this:

    myhome
    |- data (symlink to /mnt/data)
    |- subdir (extra directory, for verbose explanation)
    
    # os.path.abspath returns the absolute path, but does NOT resolve symlinks in its argument
    os.path.abspath('./')
    '/home/myhome'
    os.path.abspath('./subdir/../data')
    '/home/myhome/data'
    
    
    # os.path.realpath will resolve symlinks AND return an absolute path from a relative path
    os.path.realpath('./')
    '/home/myhome'
    os.path.realpath('./subdir/../')
    '/home/myhome'
    os.path.realpath('./subdir/../data')
    '/mnt/data'
    
    # NEITHER abspath or realpath will resolve or remove ~.
    os.path.abspath('~/data')
    '/home/myhome/~/data'
    
    os.path.realpath('~/data')
    '/home/myhome/~/data'
    
    # And the returned path will be invalid
    os.path.exists(os.path.abspath('~/data'))
    False
    os.path.exists(os.path.realpath('~/data'))
    False
    
    # Use realpath + expanduser to resolve ~
    os.path.realpath(os.path.expanduser('~/subdir/../data'))
    '/mnt/data'
    

提交回复
热议问题