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>Try something like this:</p>

<p>I assumed you read the content of the file to a string</p>

<pre><code>config_file_string = '''app_id1 {
key1 = val
key2 = val
key3 = val
}
app_id2 {
key1 = val
key2 = val
}'''

config = {}
appid = ''
for line in config_file_string.splitlines():
    print(line)
    if line.endswith('{'):
        appid = line.split()[0].strip()
        placeholder_dict = {}
    elif line.startswith('}'):
        config[appid] = placeholder_dict
    else:
        placeholder_dict[line.split('=')[0].strip()] = line.split('=')[1].strip()

print(config)
</code></pre>

<p>This returns:</p>

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

python parsing