How to load all modules in a folder?


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


I tried just converting it to a package by adding and doing from Foo import * but it didn't work the way I had hoped.

12/3/2017 7:44:10 PM

Accepted Answer

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

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('')]
4/29/2019 2:44:44 AM

Add the __all__ Variable to containing:

__all__ = ["bar", "spam", "eggs"]

See also

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow