Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python set value for specific key in properties file

We have a sample .cfg file consist of key value pair. Based on user input, we need to update the value. I was thinking to update the value using configParser but file doesn't have any section (e.g. [My Section]). Based on the documentation it needs three values to set - section, key and value. Unfortunately, I will not be able to add any section marker, as this file is used by other tasks.

What would be the another way we can set the value based on key?

File example

some.status_file_mode    =  1    # Some comment
some.example_time    = 7200     # Some comment 

As per the requirement, no change in the line. Spaces and comments needs to be same as is.

like image 694
Pinaki Mukherjee Avatar asked Aug 26 '26 05:08

Pinaki Mukherjee


1 Answers

Use NamedTemporaryFile from the tempfile module it is not too hard to build a simple parser to update a file that looks like that:

Code:

def replace_key(filename, key, value):
    with open(filename, 'rU') as f_in, tempfile.NamedTemporaryFile(
            'w', dir=os.path.dirname(filename), delete=False) as f_out:
        for line in f_in.readlines():
            if line.startswith(key):
                line = '='.join((line.split('=')[0], ' {}'.format(value)))
            f_out.write(line)

    # remove old version
    os.unlink(filename)

    # rename new version
    os.rename(f_out.name, filename)

Test Code:

import os
import tempfile
replace_key('file1', 'some.example_time', 3)

Results:

some.status_file_mode    = 1
some.example_time    = 3
like image 77
Stephen Rauch Avatar answered Aug 30 '26 04:08

Stephen Rauch