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开发者_如何学JAVA_module(self.__module__)[1])
got me what i wanted
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
This would work:
yourmodule.__file__
and if you want to find the module an object was imported from:
myobject.__module__
The path to the module's file is in module.__file__
. You can use that with os.path.dirname
to get the directory.
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.
精彩评论