问题
I'm using config.ini file to store all my configurations.
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:
[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']
If there is no way to do this, is config in json format a good option?
回答1:
ConfigParser will only ever give you those elements as strings, which you would then need to parse.
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
and the Python code would be:
import yaml
with open('config.yml') as c:
config = yaml.load(c)
config['DEFAULT']['SOMEDICT']
回答2:
A JSON file with this data could look like this:
{
"DEFAULT": {
"ADMIN": "xyz",
"SOMEDICT": {
"v1": "k1",
"v2": "k2"
},
"SOMELIST": [
"v1",
"v2"
]
}
}
Then in python:
import json
with open('config.json') as f:
config = json.load(f)
回答3:
I would suggest to use json
:
json.loads('[1, 2]') #=> [1, 2]
json.dumps([1, 2]) #=> '[1, 2]'
json.loads('{"v1": "k1", "v2": "k2"}') #=> {'v1': 'k1', 'v2': 'k2'}
json.dumps({'v1': 'k1', 'v2': 'k2'}) #=> '{"v1": "k1", "v2": "k2"}'
You will need to do dumps
before saving and loads
after reading for those fields you use JSON for.
Better solution would be to use JSON for the entire configuration file:
{
"DEFAULT": {
"ADMIN": "xyz",
"SOMEDICT": {
"v1": "k1",
"v2": "k2"
},
"SOMELIST": [
"v1",
"v2"
]
}
}
Then you could do:
conf = json.load(open('conf.json'))
json.dump(conf, open('conf.json', 'w'))
来源:https://stackoverflow.com/questions/45948411/how-to-store-dictionary-and-list-in-python-config-file