Proper use of __file__

Aahz aahz at
Tue Oct 5 18:52:57 CEST 2004

In article <10m5hc4mn8j3l04 at>,
Jeffrey Froman  <jeffrey at> wrote:
>__file__ is the name of the file in which the statement containing
>"__file__" appears. If your file reads:
>print __file__
>You can run "import foo" from the interpreter, and it will print "",
>just like if you ran "python". But if you run "print __file__" in
>the interpreter directly, NameError is raised because the call is not being
>made from any file, so __file__ is undefined.

One gotcha: in Python 2.2 and earlier, __file__ is only defined for
imported modules; "python" will raise a NameError.
Aahz (aahz at           <*>

WiFi is the SCSI of the 21st Century -- there are fundamental technical
reasons for sacrificing a goat.  (with no apologies to John Woods)

More information about the Python-list mailing list