Skip to content Skip to sidebar Skip to footer

Python Search For A String And Append To It Using Regular Expression

I need to search for a certain parameter known as jvm_args in a configuration file known as config.ini **contents of config.ini: first_paramter=some_value1 second_parameter=some_va

Solution 1:

If you "just" want to find keys and values in an ini file, I think the configparser module is a better bet than using regexps. The configparser asserts that the file has "sections", though.

Documentation for configparser is here: http://docs.python.org/library/configparser.html - useful examples at the bottom. The configparser can also be used for setting values and writing out a new .ini-file.

Input file:

$ cat /tmp/foo.ini 
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3

Code:

#!/usr/bin/python3

import configparser

config = configparser.ConfigParser()
config.read("/tmp/foo.ini")
jvm_args = config.get('some_section', 'jvm_args')
print("jvm_args was: %s" % jvm_args)

config.set('some_section', 'jvm_args', jvm_args + ' some_value4')
with open("/tmp/foo.ini", "w") as fp:
    config.write(fp)

Output file:

$ cat /tmp/foo.ini
[some_section]
first_paramter = some_value1
second_parameter = some_value2
jvm_args = some_value3 some_value4

Solution 2:

You can use re.sub

import re
import os

file = open('config.ini')
new_file = open('new_config.ini', 'w')
for line in file:
    new_file.write(re.sub(r'(jvm_args)\s*=\s*(\w+)', r'\1=\2hello', line))
file.close()
new_file.close()

os.remove('config.ini')
os.rename('new_config.ini', 'config.ini')

also check ConfigParser

Solution 3:

As both avasal and tobixen have suggested, you can use the python ConfigParser module to do this. For example, I took this "config.ini" file:

[section]framter = some_value1
second_parameter = some_value2
jvm_args = some_value3**

and ran this python script:

import ConfigParser

p = ConfigParser.ConfigParser()
p.read("config.ini")
p.set("section", "jvm_args", p.get("section", "jvm_args") + "stuff")
with open("config.ini", "w") as f:
    p.write(f)

and the contents of the "config.ini" file after running the script was:

[section]framter = some_value1
second_parameter = some_value2
jvm_args = some_value3**stuff

Solution 4:

without regex you can try:

with open('data1.txt','r') as f:
    x,replace=f.read(),'new_entry'
    ind=x.index('jvm_args=')+len('jvm_args=')
    end=x.find('\n',ind) if x.find('\n',ind)!=-1else x.rfind('',ind)
    x=x.replace(x[ind:end],replace)

with open('data1.txt','w') as f:
    f.write(x)

Post a Comment for "Python Search For A String And Append To It Using Regular Expression"