Reading configuration files without entering keys but values ​​using python configparser

I have a question regarding the configparser python module. I am using Python 3.x.

I have many .ini files that are damaged, respectively, in my oppinion defect. for example, there are values ​​without specifying a key, for example.

[SESSIONS_id]
Session_a={F34B3238-EEE5-4006-B19C-AB8CC233D8F0}
Session_b={AF2D869B-0FB1-4287-A10E-82B0884E1CFC}
Session_c={F5A7FA65-2107-4B9B-A7C2-8C89C354D4FF}
={083465AF-DC9E-4FF8-A78F-CC1DF17C84B9}

My problem here is that there is only the “Allow no values” option, I already found this, but how to handle .ini files providing values ​​without keys?

The configurator does not read it, so how to repair it?

Thank you in advance

+4
source share
1 answer

comment_prefixes="=#;", , =, :

par = configparser.ConfigParser(comment_prefixes="=#;")
par.read("foo.ini")

print(list((par["SESSIONS_id"]).items()))

[('session_a', '{F34B3238-EEE5-4006-B19C-AB8CC233D8F0}'), ('session_b', '{AF2D869B-0FB1-4287-A10E-82B0884E1CFC}'), ('session_c', '{F5A7FA65-2107-4B9B-A7C2-8C89C354D4FF}')]

, temp, configparser:

import configparser
from tempfile import TemporaryFile
t = TemporaryFile("w+")
with open("foo.ini") as f:
    t.writelines(line for line in f if not line.startswith("="))
t.seek(0)
par = configparser.ConfigParser()
par.read_file(t)

print(list((par["SESSIONS_id"]).items()))
[('session_a', '{F34B3238-EEE5-4006-B19C-AB8CC233D8F0}'), ('session_b', '{AF2D869B-0FB1-4287-A10E-82B0884E1CFC}'), ('session_c', '{F5A7FA65-2107-4B9B-A7C2-8C89C354D4FF}')]
+2

Source: https://habr.com/ru/post/1622770/


All Articles