Easier way to get the "here" path?

bukzor workitharder at gmail.com
Fri Jul 25 23:08:01 CEST 2008

I have to go into these convulsions to get the directory that the
script is in whenever I need to use relative paths. I was wondering if
you guys have a better way:

from os.path import dirname, realpath, abspath
here = dirname(realpath(abspath(__file__.rstrip("c"))))

In particular, this takes care of the case of symlinked, compiled
scripts, which is fairly common at my workplace, and I imagine in many
*nix evironments.

An illustration:
$echo "print __file__" > symlinks/path.py
$ln -s symlinks/path.py
>>> import path
>>> reload(path)
<module 'path' from 'path.pyc'>
>>> path.__file__
>>> path.__file__.rstrip("c")
>>> from os.path import abspath, realpath
>>> realpath(path.__file__.rstrip("c"))
>>> realpath(abspath(path.__file__.rstrip("c")))

More information about the Python-list mailing list