Matt
Matt

Reputation: 85

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

Upvotes: 2

Views: 294

Answers (4)

Pratik Deoghare
Pratik Deoghare

Reputation: 37172

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

Upvotes: 1

John Machin
John Machin

Reputation: 82924

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.

Upvotes: 1

sykloid
sykloid

Reputation: 101156

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

Upvotes: 1

Olivier Verdier
Olivier Verdier

Reputation: 49126

This would work:

yourmodule.__file__

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

myobject.__module__

Upvotes: 1

Related Questions