Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import files in python with a for loop and a list of names

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
like image 791
Rorschach Avatar asked Jul 27 '15 19:07

Rorschach


2 Answers

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
like image 62
Anand S Kumar Avatar answered Nov 04 '22 20:11

Anand S Kumar


myList = ['fileOne', 'fileTwo', 'fileThree']
modules = map(__import__, myList)
like image 24
open_new_tab Avatar answered Nov 04 '22 20:11

open_new_tab