Home     My Faqts     Contributors     About     Help    

faqts : Computers : Programming : Languages : Python

FAQTs repaired & updated!
Thanks for your patience...
Entry Add Entry Alert - Edit this Entry

Did You Find This Entry Useful?

2 of 4 people (50%) answered Yes
Recently 2 of 4 people (50%) answered Yes

How do I get the absolute path of a module from within the module? (os.getcwd does not do the trick)

Feb 27th, 2003 17:32

Mickel Grönroos, Michael Chermside

Say I have a executable python script /home/foo/bar/script.py. How do I 
know from within that file, which the absolute path of the file is? 
If I do os.getcwd() then it returns the directory from which I am 
executing the script, which is not what I want.
For the script itself, I'm really not sure of the
answer. Sometimes, in fact, there ISN'T a file...
you might be executing the script from stdin. However,
if the code being executed happens to be a module
(which is the case for all code EXCEPT for short,
self-contained scripts), then it's easy... simply
access the "__file__" attribute of the module object.
Obviously the answer IS available SOMEWHERE, (when
an answer exists) because if you throw an exception
it will print what file (and line) it occured on. I'm
just not sure where that comes from.
-- Michael Chermside
Great! Thanks Michael! 
Actually, my problem really concerned modules, so your answer was right 
on target.
The attribute "__file__" seems to contain the relative path to the 
module (that is, relative to the directory from which the module is 
exectuted). So computing the absolute path from within the module is 
os.path.join(os.getcwd(), __file__)

© 1999-2004 Synop Pty Ltd