How to load all modules in a folder?

后端 未结 18 1910
失恋的感觉
失恋的感觉 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:18

    Anurag Uniyal answer with suggested improvements!

    #!/usr/bin/python
    # -*- encoding: utf-8 -*-
    
    import os
    import glob
    
    all_list = list()
    for f in glob.glob(os.path.dirname(__file__)+"/*.py"):
        if os.path.isfile(f) and not os.path.basename(f).startswith('_'):
            all_list.append(os.path.basename(f)[:-3])
    
    __all__ = all_list  
    

提交回复
热议问题