Home > Backend Development > Python Tutorial > How Can I Efficiently Import All Modules from a Python Folder?

How Can I Efficiently Import All Modules from a Python Folder?

Barbara Streisand
Release: 2024-11-26 19:36:10
Original
393 people have browsed it

How Can I Efficiently Import All Modules from a Python Folder?

Loading All Modules within a Folder

When managing modules organized within a directory, it becomes necessary to import them efficiently and conveniently. This question explores a scenario where a folder (/Foo) contains Python scripts but converting it to a package using an __init__.py file and importing it using from Foo import * yields unsatisfactory results.

To address this, a comprehensive solution is proposed that automatically identifies all Python modules (.py files) within the specified folder and makes them available for import:

from os.path import dirname, basename, isfile, join
import glob

# List all Python (.py) files in the current folder
modules = glob.glob(join(dirname(__file__), "*.py"))

# Extract the module names without the file extension
__all__ = [basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]
Copy after login

By adding this code to the __init__.py file within the folder, all the modules residing in the directory become accessible for import, enabling a more streamlined approach to importing modules.

The above is the detailed content of How Can I Efficiently Import All Modules from a Python Folder?. 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