__file__ vs __FILE__

Giampaolo Rodola' gnewsg at gmail.com
Sat Nov 3 09:07:10 EDT 2007


On 3 Nov, 04:21, klenwell <klenw... at gmail.com> wrote:
> I apologize in advance for coming at this from this angle but...
>
> In PHP you have the __FILE__ constant which gives you the value of the
> absolute path of the file you're in (as opposed to the main script
> file.)  With the function dirname, this makes it easy to get the
> parent dir of a particular file from within that file:
>
> $parent_dir = dirname(__FILE__);
>
> I'm looking for the best way to accomplish this in Python.  This seems
> to work:
>
> parent_dir = os.path.normpath(os.path.join(os.path.abspath(__file__),
> '..'))
>
> Can anyone confirm the reliability of this method or suggest a better
> (one-line) method for accomplishing this?
>
> Thanks,
> Tom

This is not really 'one-line' since you have to import two modules
first, but it looks nicer...:

import sys, os
print sys.argv[0] # absolute file name
print os.path.dirname(sys.argv[0]) # absolute dir name




More information about the Python-list mailing list