How to load all modules in a folder?

后端 未结 18 1966
失恋的感觉
失恋的感觉 2020-11-22 05:37

Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:

/Foo
    bar.py
    spam.py
    eggs.py         


        
18条回答
  •  庸人自扰
    2020-11-22 06:24

    I have also encountered this problem and this was my solution:

    import os
    
    def loadImports(path):
        files = os.listdir(path)
        imps = []
    
        for i in range(len(files)):
            name = files[i].split('.')
            if len(name) > 1:
                if name[1] == 'py' and name[0] != '__init__':
                   name = name[0]
                   imps.append(name)
    
        file = open(path+'__init__.py','w')
    
        toWrite = '__all__ = '+str(imps)
    
        file.write(toWrite)
        file.close()
    

    This function creates a file (in the provided folder) named __init__.py, which contains an __all__ variable that holds every module in the folder.

    For example, I have a folder named Test which contains:

    Foo.py
    Bar.py
    

    So in the script I want the modules to be imported into I will write:

    loadImports('Test/')
    from Test import *
    

    This will import everything from Test and the __init__.py file in Test will now contain:

    __all__ = ['Foo','Bar']
    

提交回复
热议问题