2

In a project I'm working on, I need to import many files whose name are quite similar.

from TCA1 import TCA1
from TCA2 import TCA2
from TCA3 import TCA3
from TCA4 import TCA4
.
.
.
from TCA15 import TCA15

So I wonder about the possibility of putting all of these imports in a loop.

I know its ridiculous but something like:

list = ["TCA1","TCA2","TCA3"...,"TCA15"]

for lib in list:
    from lib import lib

Thanks.

3
  • 2
    If you know the names beforehand, just write the imports. Keep it clear. Commented Feb 28, 2014 at 12:28
  • What are these things you're importing? It sounds like they may be data files, in which case you may not want to use the import mechanism for this. Commented Feb 28, 2014 at 12:33
  • True, they are test cases including data. So I must import them.. Commented Feb 28, 2014 at 12:48

1 Answer 1

4

Using importlib.import_module:

import importlib

module_list = ["TCA1","TCA2","TCA3","TCA15"]

g = globals()
for lib in module_list:
    g[lib] = importlib.import_module('{0}.{0}'.format(lib))

NOTE If there's g in the module_list, this will not work. You should choose other name in such case.

Sign up to request clarification or add additional context in comments.

5 Comments

Is it possible to do something like that is equivalent to from pkg import item as name using importlib ?
@Broxigar, name = importlib.import_module(/pkg.item'), By asssinging to the name you want :)
By running the aforemention statement as: name = importlib.import_module("folder_name.package.array1") I get the error not a package
@Broxigar, If folder_name is not a package, specify package.array1. BTW, folder_name should be in sys.path.
@Broxigar, For more question, please post a separate question with concrete example (+ directory/file structure), so that others (not just me) can answer you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.