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