[Baypiggies] Reading k=v format files

Michiel Overtoom motoom at xs4all.nl
Fri Oct 9 10:09:39 CEST 2015


> On 03 Oct 2015, at 20:58, Ian Zimmerman <itz at buug.org> wrote:
> I have a file providing settings [...] It looks like this:
> Foo=bar
> Foo2=baz
> I'm looking for a short snippet to grok the file [...]

Instead of writing your own parser, you could feed ConfigParser a doctored version of your INI file.

ConfigParser doesn't have to be fed a filename, it can read a file-like object such as a StringIO 'in-memory file'.

So I first create an in-memory version of the INI file with a [configuration] section prepended to it, then feed that to ConfigParser.

    import ConfigParser
    import StringIO
    ini = open("cfgparse.ini").read()
    print "Original INI file:"
    print ini

    sect = StringIO.StringIO("[configuration]\n" + ini)
    print "Sectioned INI file:"
    print sect.getvalue()

    c = ConfigParser.ConfigParser()
    print "Foo is '%s'" % c.get("configuration", "Foo")
    print "Foo2 is '%s'" % c.get("configuration", "Foo2")

The output is:

    Original INI file:

    Sectioned INI file:

    Foo is 'bar'
    Foo2 is 'baz'


More information about the Baypiggies mailing list