用Python在xml文件中查找并替换
我对Python真的很陌生。 我有一个包含html的xml文件和一个csv文件 xml文件示例:用Python在xml文件中查找并替换,python,xml,csv,Python,Xml,Csv,我对Python真的很陌生。 我有一个包含html的xml文件和一个csv文件 xml文件示例: <example> <name id="{{2}}">{{1}}</name> <class>{{3}}</class> <modules> <module>{{4}}</module> <module>{{5}}</module>
<example>
<name id="{{2}}">{{1}}</name>
<class>{{3}}</class>
<modules>
<module>{{4}}</module>
<module>{{5}}</module>
<module>{{6}}</module>
</modules>
</example>
我必须用csv文件第二列中的值替换{{}中的值(引用在第一列的csv文件中)
我能够成功读取csv文件(没有问题)。
我正在寻找在xml文件中针对每个{{}查找和替换的解决方案
我试过了
i=1
for line in inputfile.readlines():
outputfile.write(line.replace('{{'+str(i)+'}}', 'value from 2nd colum of csv file'))
i = i +1
但它并没有取代所有的价值观
提前感谢。这段代码应该可以实现以下功能:
from csv import reader
with open('test.xml') as inputfile:
xml = inputfile.read()
with open('test.csv') as csvfile:
for row in reader(csvfile, delimiter=';'):
xml = xml.replace('{{%s}}' % row[0], row[1])
with open('output.xml', 'w') as outputfile:
outputfile.write(xml)
此代码使用了
csv
模块,这意味着您不必处理csv数据中可能出现的转义或引用的复杂性。感谢您理解我的错误html代码并回答它。刚才我编辑了我的代码。我接受你的回答。
from csv import reader
with open('test.xml') as inputfile:
xml = inputfile.read()
with open('test.csv') as csvfile:
for row in reader(csvfile, delimiter=';'):
xml = xml.replace('{{%s}}' % row[0], row[1])
with open('output.xml', 'w') as outputfile:
outputfile.write(xml)