Home > Backend Development > Python Tutorial > How Can I Dynamically Import All Modules from a Directory in Python?

How Can I Dynamically Import All Modules from a Directory in Python?

Barbara Streisand
Release: 2024-12-04 14:51:10
Original
727 people have browsed it

How Can I Dynamically Import All Modules from a Directory in Python?

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
Copy after login

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

  1. Within __init__.py in the Foo directory, list all Python (.py) files in the current folder.
  2. Use Python's __all__ variable to specify the modules to be imported.
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')]
Copy after login

Example Usage:

After creating the __init__.py file, you can now import all modules from the Foo directory using:

from Foo import *
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template