When organizing your Python code, it often becomes necessary to import multiple modules from a specific folder. One common approach involves converting the folder into a Python package by adding an __init__.py file at the root.
By creating an __init__.py file, you can import the modules within the folder as follows:
from my_package import *
However, this approach may not always be ideal, as it imports all modules from the folder, irrespective of whether you need them or not.
To selectively import modules from a folder, you can utilize the following code:
import os import inspect # Get the current folder path folder_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # Iterate over all .py files in the folder for file_name in os.listdir(folder_path): if file_name.endswith('.py') and file_name != '__init__.py': # Import the module using dynamic import module_name = file_name[:-3] module = __import__(module_name, fromlist=['*'])
Using this method, you can import specific modules within the folder by accessing them via the module_name variable.
The above is the detailed content of How to Efficiently Import Modules from a Python Folder?. For more information, please follow other related articles on the PHP Chinese website!