python - 使用python的带有字典的配置文件

标签 python python-2.7 dictionary config configobj

所以我尝试在配置文件中使用字典来将报告名称存储到 API 调用中。所以像这样:

report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}

我需要将多个 reports:apicalls 存储到一个配置值。我正在使用 ConfigObj。我在那里读过documentation , documentation它说我应该能够做到。我的代码看起来像这样:

from configobj import ConfigObj
config = ConfigObj('settings.ini', unrepr=True)
for x in config['report']:
    # do something... 
    print x

然而,当它遇到 config= 时,它会抛出一个 raise 错误。我有点迷路了。我什至复制并粘贴了他们的例子和同样的东西,“引发错误”。我正在使用 python27 并安装了 configobj 库。

最佳答案

如果您没有义务使用 INI 文件,您可以考虑使用另一种更适合处理 dict 类对象的文件格式。查看您提供的示例文件,您可以使用 JSON 文件,Python 有一个 built-in模块来处理它。

例子:

JSON 文件“settings.json”:

{"report": {"/report1": "/https://apicall...", "/report2": "/https://apicall..."}}

Python代码:

import json

with open("settings.json") as jsonfile:
    # `json.loads` parses a string in json format
    reports_dict = json.load(jsonfile)
    for report in reports_dict['report']:
        # Will print the dictionary keys
        # '/report1', '/report2'
        print report

关于python - 使用python的带有字典的配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165792/

相关文章:

python - Spark独立集群轮胎访问本地python.exe

python - fatal error : Python. h:没有这样的文件或目录

python - Shebang/选择脚本要运行的 Python 版本

python - 我尝试django runserver时,Python 2.7突然不起作用:“找不到符号:__ PyErr_ReplaceException”

python-2.7 - 升级Elasticsearch DSL

Python操作系统错误: A socket operation was attempted to an unreachable network

python - 如何将空可选参数从 Python 传递到 Excel VBA 宏

python - 具有碰撞功能的联合python字典

python Pool 映射多个参数 - 列表和变量作为输入

c# - 两个字典相乘