如何将文件夹中的python模块导入到列表中

问题描述 投票:0回答:1

我正在尝试获取我正在从事的一个有趣项目的所有模组的列表,但我不知道如何让它工作我已经研究了几个小时并且无法不明白怎么做。

这是我的代码

dirs = os.listdir('Assets/mods/scripts/')
    for i in range(len(dirs)):
        if not dirs[i].endswith('.py'):
            continue
        try:
            mods.append(importlib.__import__('Assets.mods.scripts.' + dirs[i].removesuffix('.py')))
        except Exception as e:
            print('importing error:\n', e)

每次我都可以看到它导入它(它会在控制台打印一些数字),但是当我尝试使用此函数来使用模块中的任何内容时

    for i in range(len(mods)):
        try:
            mods[i].update()
        except Exception as e:
            print('updating error:\n', e)

它只是不调用函数并告诉我

更新错误: 模块“资产”没有属性“更新”

python python-import
1个回答
0
投票
import os
import importlib.util

def import_modules_from_folder(folder_path):
    module_list = []
    for file_name in os.listdir(folder_path):
        if file_name.endswith('.py') and not file_name.startswith('__init__'):
            module_name = file_name[:-3]  # Remove '.py' extension
            module_list.append(module_name)
            module_path = os.path.join(folder_path, file_name)
            spec = importlib.util.spec_from_file_location(module_name, module_path)
            module = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(module)
    return module_list

if __name__ == "__main__":
    # Specify the path to the folder containing modules
    my_modules_folder = 'my_modules'
    other_modules_folder = 'other_modules'

    # Import modules from folders
    my_modules_list = import_modules_from_folder(my_modules_folder)
    other_modules_list = import_modules_from_folder(other_modules_folder)

    # Print the lists
    print("My Modules:", my_modules_list)
    print("Other Modules:", other_modules_list)
© www.soinside.com 2019 - 2024. All rights reserved.