I am trying to import many files. I have a list (myList) of strings that are the names of the files of the modules that I want to import. All of the files which I want to im
If you want the same effect as import <modulename>
, then one way to do it would be to import the module using importlib.import_module() , and then use globals()
function to get the global namespace and add the imported module using the same name there.
Code -
myList = {'fileOne', 'fileTwo', 'fileThree'}
import importLib
gbl = globals()
for toImport in myList:
moduleToImport = 'parentDirectory.'+toImport
gbl[moduleToImport] = importlib.import_module(moduleToImport)
Then later on you can use -
parentDirectory.fileOne.<something>
Example/Demo -
>>> import importlib
>>> globals()['b'] = importlib.import_module('b')
>>> b.myfun()
Hello
myList = ['fileOne', 'fileTwo', 'fileThree']
modules = map(__import__, myList)