I am trying to import modules dynamically in Python. Right now, I have a directory called 'modules' with two files inside (mod1.py
and mod2.py
). They are simple test functions to return time (ie. mod1.what_time('now')
returns the current time).
From my main application, I can import as follows:
sys.path.append('/Users/dxg/import_test/modules')
import mod1
Then, I can execute:
mod1.what_time('now')
This works correctly.
I am not always going to know what modules are available in the directory. I wanted to import as follows:
tree = []
tree = os.listdir('modules')
sys.path.append('/Users/dxg/import_test/modules')
for i in tree:
import i
However, I get the error:
ImportError: No module named i
What am I missing?