Python parsing an ugly configuration file
<p>I have an application generating a weird config file</p>

<pre><code>app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
</code></pre>

<p>And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable format :)</p>

<p>Any suggestions on how to do this pythonically ?
I am thinking along the lines of dict of dict</p>

<pre><code>conf = {'app_id1': {'key1' : 'val', 'key2' : 'val'},
        'app_id2' : {'key1' : 'val', 'key2' : 'val'}
       }
</code></pre>

<p>You could use regex: <code>(\w+)\s*\{([^}]*)</code> will find a <code>name { values }</code> construct, and <code>([^\s=]+)\s*=\s*([^\n]*)</code> will find <code>key = value</code> pairs.</p>

<p>As a one-liner, assuming the contents of the file are in the variable <code>s</code>:</p>

<pre><code>config= {key:dict(re.findall(r'([^\s=]+)\s*=\s*([^\n]*)', values)) for key,values in re.findall(r'(\w+)\s*\{([^}]*)', s)}
</code></pre>

python parsing