How to get the realpath of a symbolic link?

Peng Yu pengyu.ut at gmail.com
Sat Oct 31 03:03:20 EDT 2009


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



More information about the Python-list mailing list