Directory of current file

Christian Tismer tismer at appliedbiometrics.com
Thu Apr 22 12:58:05 EDT 1999


Guido van Rossum wrote:
> 
> "Fredrik Lundh" <fredrik at pythonware.com> writes:
> 
> > how about a combination?
> >
> > import sys, os
> > if __name__ == '__main__':
> >     _thisDir = sys.argv[0]
> > else:
> >     _thisDir = sys.modules[__name__].__file__
> 
> Eh, what's wrong with simply using __file__?  It's a global in your
> own module, remember!

[I think we had that some months ago, already]

> if __name__ == '__main__':
>     _thisDir = sys.path[0] or os.curdir
> else:
>     _thisDir = os.path.dirname(__file__)

Since these come up again and again, I still see no reason why 
we don't support __file__ for __main__?

Wouldn't it be much clearer to 
1) provide an absolute path for __file__ always
2) provide __file__ for __main__ as
   abs_path(sys.path[0] or os.curdir) + name_of_sciptfile?
If there is no scriptfile, well we'd take the empty string.

The other proposals are not as foolproof, since they depend
on weak stuff as os.curdir which has dynamic meaning, while
paths of files are a static thing, a "compile time" property
with early binding.

I'd like to be able to always use:

_thisDir = os.path.dirname(__file__)
_script = os.path.basename(__file__)

if _script:
   # well, we have a script file

always? Even better

_thisdir, _script = os.path.split(__file__)

What is the background to keep this thing complicated for the user
(where complicated means to use more than one function call),
instead of the above?

ciao - chris

-- 
Christian Tismer             :^)   <mailto:tismer at appliedbiometrics.com>
Applied Biometrics GmbH      :     Have a break! Take a ride on Python's
Kaiserin-Augusta-Allee 101   :    *Starship* http://starship.python.net
10553 Berlin                 :     PGP key -> http://wwwkeys.pgp.net
PGP Fingerprint       E182 71C7 1A9D 66E9 9D15  D3CC D4D7 93E2 1FAE F6DF
     we're tired of banana software - shipped green, ripens at home




More information about the Python-list mailing list