cross platform accessing paths (windows, linux ...)

Christian Heimes lists at
Thu Mar 12 21:26:31 CET 2009

Vlastimil Brom wrote:
> def path_from_pardir(path):
>     return os.path.realpath(os.path.normpath(os.path.join(os.path.dirname(__file__),
> os.pardir, path)))
> #  __file__ is substituted with sys.path[0] if not present
> real_path = path_from_pardir("txt/text_1.txt")
> The above seems to work both on windows and linux, but it very much
> looks like woodoo code for me;

The canonical way to get the directory of a Python file is


__file__ is the relative or absolute path to the .py(c) file.
os,path.abspath() makes sure it's an absolute path. os.path.dirname()
returns the name of the directory. I usually store the directory as a
global name 'HERE'.

>From here on you can traverse the file system.
os.path.abspath(os.path.join(HERE, os.pardir, somename)) gives you
"../somename" relative to the directory where your .py(c) is stored.


More information about the Python-list mailing list