How to load all modules in a folder?
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, joinimport globmodules = glob.glob(join(dirname(__file__), "*.py"))__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
Add the __all__
Variable to __init__.py
containing:
__all__ = ["bar", "spam", "eggs"]
Update in 2017: you probably want to use importlib
instead.
Make the Foo directory a package by adding an __init__.py
. In that __init__.py
add:
import barimport eggsimport spam
Since you want it dynamic (which may or may not be a good idea), list all py-files with list dir and import them with something like this:
import osfor module in os.listdir(os.path.dirname(__file__)): if module == '__init__.py' or module[-3:] != '.py': continue __import__(module[:-3], locals(), globals())del module
Then, from your code do this:
import Foo
You can now access the modules with
Foo.barFoo.eggsFoo.spam
etc. from Foo import *
is not a good idea for several reasons, including name clashes and making it hard to analyze the code.