faqts : Computers : Programming : Languages : Python

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 10 people (70%) answered Yes
Recently 7 of 10 people (70%) answered Yes


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

Feb 19th, 2008 00:07
Sheana blogs, 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__)