__file__ vs __FILE__
jeff at jmcneil.net
Sat Nov 3 04:45:54 CET 2007
The __file__ attribute is present when you run a script from a file.
If you run from the interactive interpreter, it will raise a
NameError. Likewise, I believe that in earlier versions of Python
(2.1? Pre 2.2?) it was only set within imported modules. I've used the
'os.path.realpath(os.path.pardir)' construct in a couple of scripts
myself. That ought to work within the interactive interpreter.
On Nov 2, 2007, at 11:21 PM, klenwell 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?
More information about the Python-list