os.readlink returning value

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Nov 2 05:30:15 CET 2007

En Thu, 01 Nov 2007 22:51:14 -0300, Giampaolo Rodola' <gnewsg at gmail.com>  

> I was reading os.readlink doc which says:
> readlink( path)
> Return a string representing the path to which the symbolic link
> points. The result may be either an absolute or relative pathname; if
> it is relative, it may be converted to an absolute pathname using
> os.path.join(os.path.dirname(path), result). Availability: Macintosh,
> Unix.
> ...It's not clear to me when the returning result could be absolute
> and when it could be relative.
> Could someone clarify this point?

That depends on how the symlink was created. Assume the current directory  
is /usr/home/giampaolo/any/dir
> ln -s ../foo/bar
creates a symbolic link at /usr/home/giampaolo/any/dir/bar pointing to  
../foo/bar (relative to where the link resides). That is, actually  
pointing to /usr/home/giampaolo/any/foo/bar (but this absolute path is NOT  
stored on the link itself - only ../foo/bar)

Now, a program whose current directory is /usr/home/giampaolo executes  
It will return the string "../foo/bar". One must resolve the .. reference  
relative to where the link resides, NOT relative to the current directory.  
That is, relative to any/dir. os.path.dirname("any/dir/bar") returns  
exactly that. Then, the suggested expression in the docs evaluates to  
"any/dir/../foo/bar" - it's not an absolute pathname yet, one should use  
abspath() on it. Or instead  
os.path.join(os.path.abspath(os.path.dirname(path)), result)

Gabriel Genellina

More information about the Python-list mailing list