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

前端 未结 2 483
夕颜
夕颜 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 <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
    
    0 讨论(0)
  • 2021-01-12 15:26
    myList = ['fileOne', 'fileTwo', 'fileThree']
    modules = map(__import__, myList)
    
    0 讨论(0)
提交回复
热议问题