How to get the realpath of a symbolic link?

Discussion in 'Python' started by Peng Yu, Oct 31, 2009.

  1. Peng Yu

    Peng Yu Guest

    Suppose that I have the following directory and files. I want to get
    the canonical path of a file, a directory or a symbolic link.
    For example, for 'b' below, I want to get its canonical path as
    '/private/tmp/abspath/b'.

    However, os.path.abspath('b') gives me '/private/tmp/abspath/b', but
    os.path.abspath('/tmp/abspath/b') gives me '/tmp/abspath/b'.
    The results are not the same. So, neither os.path.abspath or
    os.path.realpath gives me what I want.

    I'm wondering if there is a way to get the canonical path
    '/private/tmp/abspath/b', no matter whether the argument is 'b' or
    '/tmp/abspath/b'.

    $./test.py
    /private/tmp/abspath/a
    /private/tmp/abspath/a
    /private/tmp/abspath/a
    /private/tmp/abspath/a
    /private/tmp/abspath/a
    /private/tmp/abspath/b
    /tmp/abspath/a
    /tmp/abspath/b
    $cat test.py
    #!/usr/bin/env python

    import os.path

    print os.path.realpath('a')
    print os.path.realpath('b')
    print os.path.realpath('/tmp/abspath/a')
    print os.path.realpath('/tmp/abspath/b')

    print os.path.abspath('a')
    print os.path.abspath('b')
    print os.path.abspath('/tmp/abspath/a')
    print os.path.abspath('/tmp/abspath/b')
    $pwd
    /tmp/abspath
    $gls -Rgtra
    ..:
    total 8
    -rw-r--r-- 1 wheel 0 2009-10-31 01:52 a
    lrwxr-xr-x 1 wheel 1 2009-10-31 01:52 b -> a
    -rwx--x--x 1 wheel 312 2009-10-31 01:54 test.py
    drwx------ 5 wheel 170 2009-10-31 01:54 .
    drwxrwxrwt 23 wheel 782 2009-10-31 01:56 ..
    $gls -lgtr /tmp
    lrwxr-xr-x 1 admin 11 2009-05-21 04:28 /tmp -> private/tmp
     
    Peng Yu, Oct 31, 2009
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peng Yu
    Replies:
    0
    Views:
    547
    Peng Yu
    Oct 31, 2009
  2. Jurko Gospodnetiæ

    os.path.realpath() and os.path.abspath()

    Jurko Gospodnetiæ, Jan 11, 2011, in forum: Python
    Replies:
    1
    Views:
    521
    Adam Skutt
    Jan 12, 2011
  3. David Garamond

    non-OO realpath, basename, dirname?

    David Garamond, Dec 25, 2004, in forum: Ruby
    Replies:
    3
    Views:
    156
    Ilmari Heikkinen
    Dec 25, 2004
  4. Xeno Campanoli
    Replies:
    2
    Views:
    94
    Xeno Campanoli
    Mar 17, 2009
  5. Chris Rebert

    Re: os.path.realpath(path) bug on win7 ?

    Chris Rebert, Jan 6, 2013, in forum: Python
    Replies:
    2
    Views:
    152
    iMath
    Jan 6, 2013
Loading...

Share This Page