replace - python replacement for xml -


i have file, ff_tuningconfig_ampki.xml, contains of records such as:

<kiconfig active="%{active}" id="amp_ret_w_lin_suspicious_multiple_login_in_short_period$kiconfig"/> <kiconfig active="%{active}" id="amp_ret_w_lin_unusual_session_hour_of_day$kiconfig"/> 

i have following code:

def replace_content(path,se,search,string_replace):     root, dirs, files in os.walk(path):         filename in files:             if((se in filename)):                 file=open(os.path.join(root, filename),'r')                 lines = file.readlines()                 file=open(os.path.join(root, filename),'w')                  line in lines:                     if search in line:                     #print "found="+line                         words=line.split('=')                     #    print words                      #   print "line=" + words[0] +"="+ "8\n"                          line=line.replace(line,string_replace)                     #print "after="+line                     file.write(line)                 file.close()                 print (os.path.join(root,filename) + " replaced")  replace_content(path,'ff_tuningconfig_ampki.xml','<kiconfig active="%{active}"','<kiconfig active="true"') 

i getting below:

active="true"      <thresholds> 

instead of:

<kiconfig active="true" id="amp_ret_w_lin_unusual_session_hour_of_day$kiconfig"/> 

your problem line=line.replace(line,string_replace). take @ documentation str.replace()

line = line.replace(search,string_replace) 

to test code, have written separate script part seemed failing.

# test input s = '''<kiconfig active="%{active}" id="amp_ret_w_lin_suspicious_multiple_login_in_short_period$kiconfig"/> <kiconfig active="%{active}" id="amp_ret_w_lin_unusual_session_hour_of_day$kiconfig"/>'''  lines = s.split('\n')  # parameters search, string_replace = '<kiconfig active="%{active}"','<kiconfig active="true"'  # part of code seems failing line in lines:     if search in line:         line = line.replace(line, string_replace)     print(line) 

that lets focus on problem , makes easy , fast modify test code. once have functionality working, copy , paste working code. if part of code works have eliminated source errors , can test other parts.


as aside, no need test if search string in line before attempting replace. if search string isn't in line, str.replace() return line without modification.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -