views:

74

answers:

4

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

+1  A: 

This would work:

yourmodule.__file__

and if you want to find the module an object was imported from:

myobject.__module__
Olivier
A: 

The path to the module's file is in module.__file__. You can use that with os.path.dirname to get the directory.

sykora
this doesn't seem to work within the module eg, in the __init__ method, print self.__file__ fails, any other ideas?
Matt
self is not the module it is the instance of a class. The module is the name of the file ie the name used in an import
Mark
+1  A: 

Using the re module as an example:

>>> import re
>>> path = re.__file__
>>> print path
C:\python26\lib\re.pyc
>>> import os.path
>>> print os.path.dirname(os.path.abspath(path))
C:\python26\lib

Note that if the module is in your current working directory ("CWD"), you will get just a relative path e.g. foo.py. I make it a habit of getting the absolute path immediately just in case the CWD gets changed before the module path gets used.

John Machin
+1  A: 

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
TheMachineCharmer