Python sets values for specific keys in the properties file … here is a solution to the problem.
Python sets values for specific keys in the properties file
We have an example .cfg file consisting of key-value pairs. Based on user input, we need to update the value. I’m thinking of updating values using configParser, but the file doesn’t have any parts (e.g. [My Section]). According to the documentation, it needs to set three values – part, key, and value. Unfortunately, I can’t add any section tags because the file is already in use by other tasks.
What is another way we can set values based on keys?
File example
some.status_file_mode = 1 # Some comment
some.example_time = 7200 # Some comment
As required, the line did not change. Spaces and comments need to be left as is.
Solution
使用>NamedTemporaryFile It’s not hard to build a simple parser from the tempfile module to update a file that looks like this:
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)
Result:
some.status_file_mode = 1
some.example_time = 3