I have a Python module and I'd like to get that modules directory from inside itself. I want to do this because I have some files that I'd like to reference relative to the module.
Asked
Active
Viewed 134 times
1
-
1Possible duplicate of this? http://stackoverflow.com/questions/247770/retrieving-python-module-path – Chris Cooper Sep 28 '11 at 00:09
4 Answers
3
First you need to get a reference to the module inside itself.
mod = sys.__modules__[__name__]
Then you can use __file__
to get to the module file.
mod.__file__
Its directory is a dirname
of that.

Nam Nguyen
- 1,765
- 9
- 13
3
As you are inside the module all you need is this:
import os
path_to_this_module = os.path.dirname(__file__)
However, if the module in question is actually your programs entry point, then __file__
will only be the name of the file and you'll need to expand the path:
import os
path_to_this_module = os.path.dirname(os.path.abspath(__file__))

Mark Gemmill
- 5,889
- 2
- 27
- 22
2
I think this is what you are looking for:
import <module>
import os
print os.path.dirname(<module>.__file__)

d0nut
- 610
- 5
- 5
1
You should be using pkg_resources
for this, the resource
* family of functions do just about everything you need without having to muck about with the filesystem.
import pkg_resources
data = pkg_resources.resource_string(__name__, "some_file")

SingleNegationElimination
- 151,563
- 33
- 264
- 304