从Python文件中导入字典,其名称仅在运行时才知道

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

我目前正在制作一个系统,允许用户在新的 .py 文件中编写字典(在同一目录的单独文件夹中创建),然后访问该字典。我的创建和文件写入部分可以正常工作,但是当尝试访问用户指定的文件中的字典时会出现问题。任何帮助将不胜感激!

Here's the hierarchy:
Python(working directory)
|
|---Test(project folder)
         |
         |---main.py(the main project code)
         |
         |---SubFolder(where the .py files with each having a dictionary are stored)
                |
                |---Test.py, etc.

我尝试使用 import __ from __、__ import __(忽略空格)和 importlib.util。这些最终都不起作用,因为它只会给我一个导入错误

python python-module
1个回答
0
投票
import sys, importlib

# ...

sys.path.append(directory_with_file)
module_with_user_dict = importlib.import_module(filename_without_py_extension)
module_with_user_dict.dict_name

请记住,您将允许用户执行任意代码,因此这不是一个好主意。

(我建议让用户提供一个 JSON 文件,而不是像 @buran 在评论中建议的那样。)

© www.soinside.com 2019 - 2024. All rights reserved.