How to load all modules in a folder?

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

    Anurag's example with a couple of corrections:

    import os, glob
    
    modules = glob.glob(os.path.join(os.path.dirname(__file__), "*.py"))
    __all__ = [os.path.basename(f)[:-3] for f in modules if not f.endswith("__init__.py")]
    

提交回复
热议问题