To change Config and Properties File Value
Sometimes there will be a requirement to change the config and properties type of files, where to change it externally without opening the files. So for those type of files, below code helps solves the problem.
import fileinput
import sys
def ModConfig(File, Variable, Setting):
"""
Modify Config file variable with new setting
"""
VarFound = False
AlreadySet = False
V=str(Variable)
S=str(Setting)
# use quotes if setting has spaces #
if ' ' in S:
S = '"%s"' % S
for line in fileinput.input(File, inplace = 1):
# process lines that look like config settings #
if not line.lstrip(' ').startswith('#') and '=' in line:
_infile_var = str(line.split('=')[0].rstrip(' '))
_infile_set = str(line.split('=')[1].lstrip(' ').rstrip())
# only change the first matching occurrence #
if VarFound == False and _infile_var.rstrip(' ') == V:
VarFound = True
# don't change it if it is already set #
if _infile_set.lstrip(' ') == S:
AlreadySet = True
else:
line = "%s = %s\n" % (V, S)
sys.stdout.write(line)
# Append the variable if it wasn't found #
if not VarFound:
print "Variable '%s' not found. Adding it to %s" % (V, File)
with open(File, "a") as f:
f.write("%s = %s\n" % (V, S))
elif AlreadySet == True:
print "Variable '%s' unchanged" % (V)
else:
print "Variable '%s' modified to '%s'" % (V, S)
return
ModConfig('application.properties','application.MLModelServerURL','20.86.204.129:5000/uploadFile')
File- File that need to be changed.
Variable- Value that need to be changed inside the file.
Setting- Value that need to be added.