使用for循环和名称列表在python中导入文件

Ror*_*ach 7 python string python-import

我正在尝试导入许多文件。我有一个字符串列表(myList),这些字符串是我要导入的模块文件的名称。我要导入的所有文件都在名为parentDirectory的目录中。该目录位于此代码所在的文件夹中。

到目前为止,我有:

myList = {'fileOne', 'fileTwo', 'fileThree'}
for toImport in myList:
    moduleToImport = 'parentDirectory.'+toImport
    import moduleToImport
Run Code Online (Sandbox Code Playgroud)

这段代码只是将moduleToImport视为模块的名称,但是我希望代码理解它是字符串的变量。

This is the Error Code:
dule>
    import moduleToImport
ImportError: No module named moduleToImport
Run Code Online (Sandbox Code Playgroud)

Ana*_*mar 6

如果您希望获得与相同的效果import <modulename>,则一种方法是使用导入模块importlib.import_module(),然后使用globals()function获取全局名称空间,并在其中使用相同的名称添加导入的模块。

代码-

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

然后,您可以使用-

parentDirectory.fileOne.<something>
Run Code Online (Sandbox Code Playgroud)

示例/演示-

>>> import importlib
>>> globals()['b'] = importlib.import_module('b')
>>> b.myfun()
Hello
Run Code Online (Sandbox Code Playgroud)