Jes*_*ger 3 python dictionary config python-2.7 configobj
因此,我尝试在配置文件中使用字典来将报告名称存储到 API 调用中。所以像这样:
report = {'/report1': '/https://apicall...', '/report2': '/https://apicall...'}
Run Code Online (Sandbox Code Playgroud)
我需要存储多个报告:对一个配置值的 API 调用。我正在使用 ConfigObj。我读过那里的文档,文档说我应该能够做到。我的代码看起来像这样:
from configobj import ConfigObj
config = ConfigObj('settings.ini', unrepr=True)
for x in config['report']:
# do something...
print x
Run Code Online (Sandbox Code Playgroud)
然而,当它到达 config= 时,它会抛出一个引发错误。我有点迷失在这里。我什至复制并粘贴了他们的示例和相同的内容“引发错误”。我正在使用 python27 并安装了 configobj 库。
如果您没有义务使用INI
文件,则可以考虑使用另一种更适合处理dict
类似对象的文件格式。查看您给出的示例文件,您可以使用JSON
文件,Python 有一个内置模块来处理它。
例子:
JSON 文件“settings.json”:
{"report": {"/report1": "/https://apicall...", "/report2": "/https://apicall..."}}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)