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

前端 未结 2 490
夕颜
夕颜 2021-01-12 14:41

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 im

2条回答
  •  攒了一身酷
    2021-01-12 15:12

    If you want the same effect as import , 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.
    

    Example/Demo -

    >>> import importlib
    >>> globals()['b'] = importlib.import_module('b')
    >>> b.myfun()
    Hello
    

提交回复
热议问题