Tuesday, 17 February 2015

Find and replace in xml file with Python



I am really new to Python. I have a xml file with html inside and a csv file.


xml file example:



<example>
<name id="{{2}}">{{1}}</name>
<class>{{3}}</class>
<modules>
<module>{{4}}</say>
<module}">{{5}}</say>
<module>{{6}}</say>
</modules>
</example>


CSV file with two columns:



1;Alex
2;345
3;10
4;math
5;pysics
6;chemistry


I have to replace values inside {{}} (references are in csv file in first column) with the values in second column of csv file.


I am able to read csv file successfully (No problem with that). I am looking for solution to find and replace in xml file against each {{}}.


I tried



i=1
for line in inputfile.readlines():
outputfile.write(line.replace('{{'+str(i)+'}}', 'value from 2nd colum of csv file'))
i = i +1


but it is not replacing all the values.


Thanks in advance.


No comments:

Post a Comment