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 import are in a directory called parentDirectory. This directory is in the folder that this code is in.
What I have so far is:
myList = {'fileOne', 'fileTwo', 'fileThree'}
for toImport in myList:
moduleToImport = 'parentDirectory.'+toImport
import moduleToImport
This code just treats moduleToImport as a module's name, but I want the code to understand that it is a variable for a string.
This is the Error Code:
dule>
import moduleToImport
ImportError: No module named moduleToImport
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With