How to load all modules in a folder?

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

    List all python (.py) files in the current folder and put them as __all__ variable in __init__.py

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

提交回复
热议问题