Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python在xml文件中查找并替换_Python_Xml_Csv - Fatal编程技术网

用Python在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>

我对Python真的很陌生。 我有一个包含html的xml文件和一个csv文件

xml文件示例:

<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)