Question

One can get the path of the current script with os.path.pathname(sys.argv[0]). But how can i get the path of a module which isn't the executed script and instead the script imported the module. I need it to read a configuration file for a module which should be in the same folder as the module but the module could be installed anywhere.

Was it helpful?

Solution

import os
import your_module

# Get directory of your module
print os.path.dirname(your_module.__file__)

Demo:

import os
import re

print os.path.dirname(re.__file__)

Output:

/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top