是否有一个解析器来读取和存储要写入的数据类型?文件格式必须产生可读性。搁置不提供。
发布于 2011-06-19 21:57:24
使用ConfigParser类读取ini文件格式的配置文件:
http://docs.python.org/library/configparser.html#examples
ini文件格式不存储所存储的值的数据类型(您需要在读回数据时知道它们)。您可以通过将值编码为json格式来克服此限制:
import simplejson
from ConfigParser import ConfigParser
parser = ConfigParser()
parser.read('example.cfg')
value = 123
#or value = True
#or value = 'Test'
#Write any data to 'Section1->Foo' in the file:
parser.set('Section1', 'foo', simplejson.dumps(value))
#Now you can close the parser and start again...
#Retrieve the value from the file:
out_value = simplejson.loads(parser.get('Section1', 'foo'))
#It will match the input in both datatype and value:
value === out_value由于是json,所以存储值的格式是人类可读的。
发布于 2011-06-19 22:33:41
您可以使用以下函数
def getvalue(parser, section, option):
    try:
        return parser.getint(section, option)
    except ValueError:
        pass
    try:
        return parser.getfloat(section, option)
    except ValueError:
        pass
    try:
        return parser.getbool(section, option)
    except ValueError:
        pass
    return parser.get(section, option)发布于 2017-08-09 15:05:19
有了configobj库,它就变得非常简单。
import sys
import json
from configobj import ConfigObj
if(len(sys.argv) < 2):
    print "USAGE: pass ini file as argument"
    sys.exit(-1)
config = sys.argv[1]
config = ConfigObj(config)现在,您可以使用config作为字典来提取所需的配置。
如果你想把它转换成json,那也很简单。
config_json = json.dumps(config)
print config_jsonhttps://stackoverflow.com/questions/6402753
复制相似问题