Search code examples
pythonmoduledirname

Finding a module's directory


How can I find what directory a module has been imported from, as it needs to load a data file which is in the same directory.

edit:

combining several answers:

module_path = os.path.dirname(imp.find_module(self.__module__)[1])

got me what i wanted


Solution

  • If you want to modules directory by specifying module_name as string i.e. without actually importing the module then use

    def get_dir(module_name):
        import os,imp
        (file, pathname, description) = imp.find_module(module_name)
        return os.path.dirname(pathname)
    
    print get_dir('os')
    

    output:

    C:\Python26\lib
    


    foo.py

    def foo():
        print 'foo'
    

    bar.py

    import foo
    import os
    print os.path.dirname(foo.__file__)
    foo.foo()
    

    output:

    C:\Documents and Settings\xxx\My Documents
    foo