【问题标题】:Python ini parserPython ini 解析器
【发布时间】:2011-09-18 04:00:48
【问题描述】:

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

【问题讨论】:

  • ConfigParser 没有做你想做的事吗?
  • 我需要支持自动类型检测。 ConfigParser 将所有内容都读取为字符串。
  • 更正 - ConfigParser 允许您读取不同数据类型的值,但您需要在读取时知道每个数据类型的类型。
  • 你知道配置项应该是什么类型,还是你想读取任意的ini文件?

标签: python file ini configparser


【解决方案1】:

有了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_json

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我需要一个在读取记录类型时自动检测的解析器。
    • 然后把字符串存成json格式,这样你也能读取类型吗?
    【解决方案3】:

    您可以使用以下功能

    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)
    

    【讨论】:

    • 如果你存储一个布尔值(在 ini 文件中存储为 1 或 0),你会得到一个 int 返回。
    • 这是一个重要的限制,是的。不幸的是,那时不可能找出确切的含义。 (与许多可能的值一样)。幸运的是,如果你像 if getvalue(parser, "asection", "boollookslikeint"): 那样使用它不会有问题
    • 最终,如果 OP 只是以 ini 文件格式存储内容 - 如果没有更多元数据,他将无法取回数据类型。
    • 我找到了pyfig,但他只能阅读。 bitbucket.org/alecwh/pyfig/overview player_age/float = 19
    • Pyfig 也不会自动检测类型。实际上不可能这样做:值1 可以是布尔值、整数、浮点数或字符串。 true 可以是布尔值或字符串。
    猜你喜欢
    • 2019-03-09
    • 2014-11-26
    • 2017-06-06
    • 2013-04-11
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多