Loading Modules Dynamically from a Directory
Question:
Importing modules from a specific directory can be challenging. Consider the following directory structure:
/Foo bar.py spam.py eggs.py
Importing the modules using __init__.py and from Foo import * does not yield the desired result. How can one import all modules from this directory dynamically?
Answer:
Create an init__.py File with __all Variable
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')]
Example Usage:
After creating the __init__.py file, you can now import all modules from the Foo directory using:
from Foo import *
This will dynamically import all available modules within the Foo directory.
The above is the detailed content of How Can I Dynamically Import All Modules from a Directory in Python?. For more information, please follow other related articles on the PHP Chinese website!