Update or change value of a key in .cong file in python

Viewed 12

I have .conf file with Key Value pair like -

key1=value1
key2=value2
key3=value3

In my python code I have dictionary like

conf = {'key1' : 'newvalue1', 'key3' : 'newvalue3'}

I want to update value of given keys from dictionary in file by using python. How can I achieve it. I tried below but it is not working

def save_settings(conf):
for line in fileinput.input(files=["%s" % (CONF)], inplace=1):
    line = re.sub('key1=.*', 'key1=%s' % (conf['key1']), line.rstrip())
    line = re.sub('key3=.*', 'key1=%s' % (conf['key1']), line.rstrip())
    print(line)
return "true"
1 Answers

Best solution would be to use a standard python library like Configparser. Alternatively you can do a simple approach.

First we read the old conf file:

with open("conf.conf") as f:
    conf_lines = [line.strip().split("=") for line  in f.readlines()]

Here our conf_lines look like:

[['key1', 'value1'], ['key2', 'value2'], ['key3', 'value3']]

since this is a nested list, we convert this into dict object

conf_lines = {line[0]: line[1] for line in conf_lines}

Now we have conf_lines as dict:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

Our new values are also in dict as conf = {'key1' : 'newvalue1', 'key3' : 'newvalue3'} so we can just update conf_lines using

conf_lines.update(conf)

now our conf_lines look like

{'key1': 'newvalue1', 'key2': 'value2', 'key3': 'newvalue3'}

And we write this change into conf file:

with open("new_conf.conf", "w") as f:
    for key, value in conf_lines.items():
        f.write(f"{key}={value}" + os.linesep)
Related