You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过文件路径导入Python文件中的字典变量

解决方案

方法1:使用importlib.util加载任意路径的模块

这是最规范的Python模块加载方式,支持任意文件路径,无需文件与调用代码在同一目录:

import importlib.util

def load_dict_from_path(file_path):
    # 创建模块规范
    spec = importlib.util.spec_from_file_location("custom_dict", file_path)
    # 加载模块对象
    module = importlib.util.module_from_spec(spec)
    # 执行模块内的代码
    spec.loader.exec_module(module)
    # 返回目标字典变量
    return module.dict

调用示例:

my_dict = load_dict_from_path("/absolute/path/to/your/dictionary.py")
print(my_dict)

方法2:改进AST解析适配赋值语句

通过遍历AST节点,精准定位dict = {...}赋值语句,提取字典内容解析:

import ast

def load_dict_via_ast(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read()
    # 解析文件为AST树
    tree = ast.parse(content)
    for node in ast.walk(tree):
        # 筛选赋值语句节点
        if isinstance(node, ast.Assign):
            # 检查赋值目标是否为"dict"变量
            for target in node.targets:
                if isinstance(target, ast.Name) and target.id == "dict":
                    # 将AST字典节点转为Python对象
                    return ast.literal_eval(node.value)
    raise ValueError("文件中未找到名为dict的变量")

方法3:正则提取字典内容(简单场景适用)

如果文件格式固定(仅含dict = {...}核心内容),可通过正则匹配字典字符串后解析:

import re
import ast

def load_dict_via_regex(file_path):
    with open(file_path, "r", encoding="utf-8") as f:
        content = f.read()
    # 匹配dict赋值语句后的字典部分
    match = re.search(r'dict\s*=\s*({.*?})', content, re.DOTALL)
    if not match:
        raise ValueError("未找到有效字典内容")
    dict_str = match.group(1)
    return ast.literal_eval(dict_str)

注意:正则方法依赖文件格式稳定,若文件存在复杂注释或多行嵌套结构,需调整正则表达式适配。

内容的提问来源于stack exchange,提问作者crazy lizard

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 13:49:53