The other answer by @Mureinik is good, but simply doing - importlib.import_module(file_name)
is not enough. As given in the documentation of importlib
-
importlib.import_module(name, package=None)
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be specified to the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod). The specified module will be inserted into sys.modules and returned.
importlib.import_module
simply returns the module object, it does not insert it into the globals
namespace, so even if you import the module this way, you cannot later on use that module directly as filename1.<something>
(or so).
Example -
>>> import importlib
>>> importlib.import_module('a')
<module 'a' from '/path/to/a.py'>
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined
To be able to use it by specifying the name, you would need to add the returned module into the globals()
dictionary (which is the dictionary for the global namespace). Example -
gbl = globals()
for i in range(0, 51):
file_name = 'myfile{}'.format(i)
try:
gbl[file_name] = importlib.import_module(file_name)
except ImportError:
pass #Or handle the error when `file_name` module does not exist.
It might be also be better to except ImportError
incase file_name
modules don't exist, you can handle them anyway you want.