python - Text replacing is not working -
i have list of integers looks like:
i = [1020 1022 .... ]
i need open xml file stored .txt , each entry includes
settings="keys1029"/>
i need iterate through records replacing each numbers in "keys1029" list entry. instead of having:
....settings="keys1029"/> ....settings="keys1029"/>
we have:
....settings="keys1020"/> ....settings="keys1022"/>
so far have:
import os out = [1020,1022] open('c:\xml1.txt') f1,open('c:\somefile.txt',"w") f2: #somefile.txt temporary file text = f1.read() item in out: text = text.replace("keys1029","keys"+str(item),1) f2.write(text) #rename temporary file real file os.rename('c:\somefile.txt','c:\xml1.txt')
this replacing:
....settings="keys1029"/> ....settings="keys1029"/>
with
....settings="keys1"/> ....settings="keys1"/>
any idea i'm doing wrong?
thank in advance,
i suggest different , more robust algorithm:
text = """ bla bla bla 1029 , 1029 bla bla bla 1029 bla bla bla 1029 , 1029 """ out = [1020,1022] cnt_repl=0 while true: text_new = text.replace("1029", str(out[cnt_repl%(len(out))]),1) if text_new==text: break cnt_repl+=1 text=text_new print text
for example text returns:
bla bla bla 1020 , 1022 bla bla bla 1020 bla bla bla 1022 , 1020
Comments
Post a Comment