this is my python script below, I try to use sub() to replace all the values between <StartNum> and </StartNum> by using a variable continous number n Then, write the results to a new text file.
any people could point out the mistake?
import re
f1 = open('name.xml', 'r')
f2 = open('result.txt', 'w')
data=f1.read()
n=5000
for line in f1:
f2.write(re.sub('<StartNum>(.*)</StartNum>', r'<StartNum>%s</StartNum>' % str(n), data))
if "<StartNum>" in line:
n=n+1
f1.close()
f2.close()
You have a few problems with your code.
readlinesmethod is probably the most straight forward.re.sub, you were usingdataas the source, while you actually want the line.There are other things you could do to improve the code, but the ones listed above are pretty necessary.
I am guessing this will likely do what you want.
Given names.xml of
result.txt will be: