How to obtain python file path

Ben Hutchings do-not-spam-ben.hutchings at
Thu Apr 3 18:42:09 CEST 2003

Please don't top-post.

In article <20030402115351679-0500 at>, 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]
            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