using variable in import command

Use importlib module if you want to import modules based on a string:

>>> import importlib
>>> os = importlib.import_module('os')
>>> os
<module 'os' from '/usr/lib/python2.7/os.pyc'>

When you do something like this:

>>> k = 'os'
>>> import k

then Python still looks for file named k.py, k.pyc etc not os.py as you intended.

Leave a Comment