Python - 迭代CSV行并用XML替换

时间:2016-07-26 20:03:34

标签: python xml csv

我有一个 CSV,其中包含我想要在XML模板中替换的值。为每行生成 XML ,其文件名基于同一行中的数据。这些基本上只是带有查找和替换的模板的副本。 到目前为止,我已经使文件名正常工作,但XML文件不会根据行替换其数据,而是仅替换第3行第10列中的数据。我希望让它遍历一系列行并为每个创建新文件。我不知道这里出了什么问题。

CSV片段:

COLUMN_K, COLUMN_L
K02496.ai, Test
K02550.ai, Test
K02686.ai, Test
K02687.ai, Test

现有的XML模板代码段

  <gmd:resourceFormat>
    <gmd:MD_Format>
      <gmd:name>
        <gco:CharacterString>COLUMN_K</gco:CharacterString>
      </gmd:name>

Python代码

import csv

exampleFile = open('U:\PROJECTS\Technical Graphics\metadata.csv')
exampleReader = csv.reader(exampleFile)
exampleData = list(exampleReader) #CSV as list

with open('U:\PROJECTS\Technical Graphics\COLUMN_K_edited.xml') as inputfile: #template XML
    xml = inputfile.read()

with open('U:\PROJECTS\Technical Graphics\metadata.csv') as csvfile:
    for row in reader(csvfile, delimiter=';'):
        for i in range(5): #range of 5 rows
           xml = xml.replace('COLUMN_K', exampleData[i+3][10]) 
#Only taking value from row 3, COLUMN_K- Need values from row 3 on
           xml = xml.replace('COLUMN_L', exampleData[i+3][11]) 
#Only taking value from row 3, COLUMN_L- Need values from row 3 on    
            with open('U:\PROJECTS\Technical Graphics\XXX' + str((exampleData[i+3][10])) + ".xml", 'w') as outputfile: 
 #Correctly outputs multiple filenames based on COLUMN_K value
                outputfile.write(xml) #writes multiple XMLs

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

您已经提到过&#39; COLUMN_F&#39;在xml标记中,您正试图替换&#39; COLUMN_E&#39;在代码中

xml = xml.replace(&#39; COLUMN_E&#39;,exampleData [i + 3] [10])

答案 2 :(得分:0)

我能够通过将循环移动到代码的最顶层来解决这个问题。 问题是它正在替换文本但后来找不到“COLUMN_ *”,因为它已被替换为值。将循环移动到顶部解决了这个问题。

import csv

    for i in range(5):  #loops through 5 rows
        exampleFile = open('U:\PROJECTS\Technical Graphics\metadata.csv')  #CSV file
        exampleReader = csv.reader(exampleFile)
        exampleData = list(exampleReader) #turns CSV into list

        with open('U:\PROJECTS\Technical Graphics\COLUMN_K_edited.xml') as inputfile:
            xml = inputfile.read() #XML template file

        with open('U:\PROJECTS\Technical Graphics\metadata.csv') as csvfile:

            for row in reader(csvfile, delimiter=';'): #defines CSV delimiter

                    with open('U:\PROJECTS\Technical Graphics\XXX' + str((exampleData[i+3][10])) + ".xml", 'w') as outputfile:
                    #Filename of XMLs based on column 10 data        
                        xml = xml.replace('COLUMN_I', str((exampleData[i+3][8])))
                        xml = xml.replace('COLUMN_K', str((exampleData[i+3][10])))


                        outputfile.write(xml) #writes 5 XML files