Directory of current file
Guido van Rossum
guido at eric.cnri.reston.va.us
Thu Apr 22 08:25:30 EDT 1999
"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!
> _thisDir = os.path.split(_thisDir)[0]
One more refinement: instead of os.path.split(x)[0], use
os.path.dirname(x).
The whole thing could become a one-liner:
_thisDir = os.path.dirname(__name__ == '__main__' and sys.argv[0] or __file__)
You could also use the little-known fact that sys.path[0] is the
script's directory; or the empty string if it's the current directory:
if __name__ == '__main__':
_thisDir = sys.path[0] or os.curdir
else:
_thisDir = os.path.dirname(__file__)
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list