How to parse this file using python?
<p>I have a file with contents like</p>

<pre><code>[Input:1]
Name=Feature1
Transform=Linear
Slope=1
Intercept=0

[Input:4]
Name=Feature2
Transform=Linear
Slope=1
Intercept=0

[Input:2]
Expression=( if ( &gt; Var 10000000) ( - Var 10000000) ( + Var 10000000))
Transform=Freeform

[Input:3]
Transform=FreeForm
Expression=(if (&gt; Var2 1) Var2 0)
Slope=1
Intercept=0
</code></pre>

<p>I need to create a list of objects with each object containing fields given above. Thus [Input:1] will correspond to object 1, there will be 4 variables inside given as Name, Transform, Slope and Intercept. The value ( in string) of that fields will be "Feature1", "Linear", "1" and "0" respectively. Note that each object can have different fields. How do I do this in python?</p>

<p>Try:</p>

<pre><code>try:
    # Python 2
    import ConfigParser as cfgp
except:
    # Python 3
    import configparser as cfgp

class MyObject:
    def __getitem__(self, attr):
        return getattr(self, attr)

conf = cfgp.ConfigParser()
conf.optionxform = str
conf.read('sample.cfg')
objects = []
for section in conf.sections():
    obj = MyObject()
    for field, value in conf.items(section):
        setattr(obj, field, value)
    objects.append(obj)
</code></pre>

<p>Then, you can get the field values by:</p>

<pre><code>for obj in objects:
    print(obj.Transform)    # or obj.Name, etc
    print(obj['Transform']) # or obj['Name'], etc
</code></pre>

python parsing text