Import files in python with for loop and list of names

I am trying to import a lot of files. I have a list (myList) of strings that are the names of the modules files that I want to import. All the files I want to import are in a directory called parentDirectory. This directory is located in the folder in which this code is located.

What I still have:

myList = {'fileOne', 'fileTwo', 'fileThree'}
for toImport in myList:
    moduleToImport = 'parentDirectory.'+toImport
    import moduleToImport

This code simply considers moduleToImport as the name of the module, but I want the code to understand that it is a variable for the string.

This is the Error Code:
dule>
    import moduleToImport
ImportError: No module named moduleToImport
+4
source share
2 answers

, import <modulename>, importlib.import_module(), globals() .

-

myList = {'fileOne', 'fileTwo', 'fileThree'}
import importLib
gbl = globals()
for toImport in myList:
    moduleToImport = 'parentDirectory.'+toImport
    gbl[moduleToImport] = importlib.import_module(moduleToImport)

-

parentDirectory.fileOne.<something>

/ -

>>> import importlib
>>> globals()['b'] = importlib.import_module('b')
>>> b.myfun()
Hello
+3
myList = ['fileOne', 'fileTwo', 'fileThree']
modules = map(__import__, myList)
+2

All Articles