简体   繁体   English

通过ConfigParser获得的Typecast词典值

[英]Typecast dictionary values obtained via ConfigParser

I am using ConfigParser to get a large number of variables that are set in a configuration file, CONFIG.txt. 我正在使用ConfigParser来获取在配置文件CONFIG.txt中设置的大量变量。

import ConfigParser
parser = ConfigParser.ConfigParser()
parser.read('CONFIG.txt')
settings = dict(parser.items('some_section'))

I actually create several dictionaries from the different config file sections and have stored them in a nested format. 实际上,我从不同的配置文件部分创建了几个字典,并将它们以嵌套格式存储。 I want to keep the variables stored in dictionary format as it makes it easy to pass around many at a time to various functions. 我想将变量保存为字典格式,因为这样可以轻松地一次将多个变量传递给各种函数。 ConfigParser stores all the text from the file as strings. ConfigParser将文件中的所有文本存储为字符串。 Is there a quick way to typecast the variables properly. 有没有一种快速的方法来正确类型化变量。 Some of the variables are lists of strings, some strings, some integers and some floats. 一些变量是字符串列表,一些字符串,一些整数和一些浮点数。 I can format the config file how I like and don't even really need to use ConfigParser if someone can suggest a more suitable alternative. 我可以按照自己喜欢的方式格式化配置文件,如果有人可以提出更合适的替代方案,甚至不需要使用ConfigParser。

Thanks. 谢谢。

Given that you can use whatever format you like, I'd say the simplest approach is JSON: 鉴于您可以使用任何喜欢的格式,我想说最简单的方法是JSON:

$ cat a.json
{
  "categ": {
    "one": 0.3,
    "two": 123,
    "three": "hello",
    "four": true
  },
  "other": [1, 2, 3]
}
$ python -c 'import json; print json.load(open("a.json"))'
{u'categ': {u'four': True, u'three': u'hello', u'two': 123, u'one': 0.3}, u'other': [1, 2, 3]}

You get arbitrary nested and basic types for free, and very easy loading using the json module. 您可以免费获得任意嵌套和基本类型,并且可以使用json模块轻松加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM