Python ini解析器

Python ini解析器,python,file,ini,configparser,Python,File,Ini,Configparser,是否有一个解析器来读取和存储要写入的数据类型? 必须使用文件格式才能生成可读的文件。 搁置不提供。使用ConfigParser类读取ini文件格式的配置文件: ini文件格式不存储存储的值的数据类型(在读回数据时需要知道它们)。您可以通过将值编码为json格式来克服此限制: import simplejson from ConfigParser import ConfigParser parser = ConfigParser() parser.read('example.cfg') va

是否有一个解析器来读取和存储要写入的数据类型? 必须使用文件格式才能生成可读的文件。
搁置不提供。

使用
ConfigParser
类读取ini文件格式的配置文件:

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,存储值的格式是人类可读的。

您可以使用以下函数

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)

使用
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)

ConfigParser不执行您想要的操作吗?我需要支持自动类型检测。ConfigParser将所有内容读取为字符串。更正-ConfigParser允许您读入不同数据类型的值,但在读取时需要知道每个数据类型的类型。您知道配置项应该是什么类型吗,或者您正在尝试读取任意ini文件?我需要一个解析器,在读取记录类型时自动检测。然后以json格式存储字符串,这样您也可以读取类型?如果您存储一个布尔值(作为1或0存储在ini文件中),您将返回一个int。这是一个重要的限制,是的。不幸的是,当时不可能找出确切的含义。(与许多可能值的情况一样)。幸运的是,如果你像使用
if getvalue(解析器,“asection”,“boollookslikeint”):
那样使用它不会有问题,最终如果OP只是以ini文件格式存储内容,如果没有进一步的元数据,他将无法恢复数据类型。我发现pyfig,但他只能阅读。player_age/float=19Pyfig也不会自动检测类型。实际上不可能这样做:值
1
可以是布尔值、整数、浮点值或字符串
true
可以是布尔值或字符串。
config_json = json.dumps(config)
print config_json