如何从多文件夹导入字典以构建Pandas DataFrame
解决方法
假设每个form.py里的目标字典名为chart_config(如果实际名字不同,替换成你自己的字典名即可),下面是两种可行的实现方式:
方法一:使用importlib动态导入模块(推荐)
这种方式符合Python模块导入规范,能降低执行未知代码的风险:
import os import pandas as pd import importlib.machinery # 初始化存储所有字典的列表 dict_list = [] # 遍历目录查找所有form.py文件 for root, dirs, files in os.walk(os.environ["JUPYTER_ROOT"] + "/charts/"): for file in files: if file.endswith("form.py"): file_path = os.path.join(root, file) # 动态加载模块 loader = importlib.machinery.SourceFileLoader("temp_module", file_path) module = loader.load_module() # 提取目标字典并添加到列表 if hasattr(module, "chart_config"): dict_list.append(module.chart_config) # 清理已加载模块,避免重复导入冲突 del module # 转换为Pandas DataFrame df = pd.DataFrame(dict_list)
方法二:使用exec直接执行文件内容
如果所有form.py都是你自己编写的安全文件,这种方式更简洁:
import os import pandas as pd dict_list = [] for root, dirs, files in os.walk(os.environ["JUPYTER_ROOT"] + "/charts/"): for file in files: if file.endswith("form.py"): file_path = os.path.join(root, file) # 读取文件内容并执行,获取字典 local_namespace = {} with open(file_path, "r", encoding="utf-8") as f: exec(f.read(), globals(), local_namespace) # 提取目标字典 if "chart_config" in local_namespace: dict_list.append(local_namespace["chart_config"]) # 生成最终DataFrame df = pd.DataFrame(dict_list)
关键提示
- 务必将代码中的
chart_config替换为你每个form.py里实际的字典变量名 - 代码中的判断逻辑会跳过没有目标字典的文件,避免报错
- 最终生成的DataFrame会自动把字典的键作为列名,每个字典对应一行数据
内容的提问来源于stack exchange,提问作者Nemra Khalil
相关产品推荐
相关产品推荐

