How to obtain python file path

Ben Hutchings do-not-spam-ben.hutchings at businesswebsoftware.com
Thu Apr 3 11:42:09 EST 2003


Please don't top-post.

In article <20030402115351679-0500 at news.covad.net>, Dan Grassi wrote:
> This works only if the python script is imported, not if it is executed 
> directly.

Well then:

    def mydir():
        import os.path, sys
        if __name__ == '__main__':
            filename = sys.argv[0]
        else:
            filename = __file__
        return os.path.abspath(os.path.dirname(filename))

> Gee, I'm surprised that this is such a difficult thing to do yet 
> conceptually simple.

I don't think it is all that simple, but maybe I've just got used to the
idea that files don't know (and don't need to know) their names.




More information about the Python-list mailing list