如何在python配置文件中存储字典和列表? [英] How to store dictionary and list in python config file?
问题描述
我正在使用config.ini文件存储所有配置。
I'm using config.ini file to store all my configurations.
我需要在配置文件中存储字典和列表,并在我的文件中解析它使用configparser的main.py文件。谁能告诉我我该怎么做?
I need to store a dictionary and a list in the config file and parse it in my main.py file using configparser. Can anyone please tell me how do I go about doing that?
config.ini:
config.ini:
[DEFAULT]
ADMIN = xyz
SOMEDICT = {'v1': 'k1', 'v2': 'k2'}
SOMELIST = [v1, v2]
main.py:
config = configparser.ConfigParser()
config.read('config.ini')
secret_key = config['DEFAULT']['ADMIN']
如果没有办法,以json格式配置是否是一个好选择?
If there is no way to do this, is config in json format a good option?
推荐答案
ConfigParser只会将这些元素作为字符串提供给您,然后您需要对其进行解析。
ConfigParser will only ever give you those elements as strings, which you would then need to parse.
作为替代,YAML是易于阅读的配置文件的不错选择。您的文件可能看起来像这样:
As an alternative, YAML is a good choice for configuration files, since it is easily human readable. Your file could look like this:
DEFAULT:
ADMIN: xyz
SOMEDICT:
v1: k1
v2: k2
SOMELIST:
- v1
- v2
,Python代码将是:
and the Python code would be:
import yaml
with open('config.yml') as c:
config = yaml.load(c)
config['DEFAULT']['SOMEDICT']
这篇关于如何在python配置文件中存储字典和列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!