python – How to load all modules in a folder?

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 __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)]

Add the __all__ Variable to __init__.py containing:

__all__ = [bar, spam, eggs]

See also http://docs.python.org/tutorial/modules.html

python – How to load all modules in a folder?

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 bar
import eggs
import 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 os
for 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.bar
Foo.eggs
Foo.spam

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

Leave a Reply

Your email address will not be published.