__file__

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Apr 11 02:49:38 EDT 2007


En Tue, 10 Apr 2007 21:20:51 -0300, 7stud <bbxx789_05ss at yahoo.com>  
escribió:

> I'm having trouble understanding what the definition of __file__ is.
> With this program:
>
> ------
> #data.py:
>
> def show():
>     print __file__
>
> if __name__ == "__main__":
>     show()
> -------
>
> if I run data.py with the prompt pointing to the directory that
> contains data.py, then __file__ produces a filename:
>
> data.py

[cut: other examples showing different paths to data.py]

__file__ corresponds to the filename used to locate and load the module,  
whatever it is. When the module is found on the current directory  
(corresponding to '' in sys.path), you get just the filename; if sys.path  
contains a relative path, that's what you get; the same for any absolute  
path.
Whatever path worked to find and load the module, that's stored as  
__file__.

If you plan to use it, it's a good idea to make it early into an absolute  
path (using os.path.abspath(__file__)) just in case the current directory  
changes.

> And some modules have __file__ in their __dict__ and some don't:
> pprint.pprint(sys.__dict__)

sys is a builtin module: no sys.py/sys.pyc exists, so __file__ is  
meaningless.

-- 
Gabriel Genellina




More information about the Python-list mailing list