How to load all modules in a folder? How to load all modules in a folder? python python

How to load all modules in a folder?

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

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('')]

Add the __all__ Variable to containing:

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

See also

Update in 2017: you probably want to use importlib instead.

Make the Foo directory a package by adding an In that 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 == '' 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


etc. from Foo import * is not a good idea for several reasons, including name clashes and making it hard to analyze the code.