为什么我的函数没有迭代并将所有CSV数据写入我的XML模板



我正在编写一个代码,旨在从csv文件中抓取数据并将其写入xml模板,然后以标题作为输出+记录号导出文件。这就是问题所在,我的代码正确地创建了所有具有正确命名的文件,我使用了几个print语句来调试我的代码,我的for循环正确地循环了我的csv数据,计数器输出是15(我在我的csv文件中有15行),所以我认为这部分是有效的,我使用元素树库以便写入我的xml模板并将输出文件保存为xml文件。当我打开所有的输出文件并意识到它们都有相同的记录输入时,我卡住了这是csv文件的第一行,我不知道我的错误在哪里,有人可以帮助我吗

下面是我的代码:
from xml.etree import ElementTree as ET 
def Task():
""" This Function uses an XML template and replaces certain variables (parameters)
with data in a csv file :)"""
CSV_File = open('records1.csv', 'r', encoding = 'UTF-8')
tree = ET.parse('Template1.xml')
root = tree.getroot()
count = 0
for line in CSV_File:
x = line.split(',')
count +=1
print(x)
for node in root.getiterator():
if node.attrib.get('val') == 'X1':
node.attrib['val'] = x[0]
if node.attrib.get('val') == 'X2':
node.attrib['val'] = x[1]
if node.attrib.get('val') == 'X3':
node.attrib['val'] = x[2]
if node.attrib.get('val') == 'X4':
node.attrib['val'] = x[3]
if node.attrib.get('val') == 'X5':
node.attrib['val'] = x[4]
if node.attrib.get('val') == 'X6':
node.attrib['val'] = x[5]
if node.attrib.get('val') == 'X7':
node.attrib['val'] = x[6] 
XML_File= open('output'+str(count)+'.xml', 'wb') 
tree.write(XML_File)
XML_File.close()

您正在编辑XMLtree对象以保存它。通过编辑它的值,它将只在第一个循环上工作,因为在那之后你不会找到val = 'X1'的节点,而是val = the_value_u_set_before的节点。
所以你实际上从来没有在第一个循环后匹配if语句,在它结束时,你总是保存相同的树。
将模板的解析移到for循环

from xml.etree import ElementTree as ET 
def Task():
""" This Function uses an XML template and replaces certain variables (parameters)
with data in a csv file :)"""
CSV_File = open('records1.csv', 'r', encoding = 'UTF-8')
count = 0
for line in CSV_File:
x = line.split(',')
// moved the next 2 lines inside the loop
tree = ET.parse('Template1.xml')
root = tree.getroot()
count +=1
print(x)
for node in root.iter():
if node.attrib.get('val') == 'X1':
node.attrib['val'] = x[0]
if node.attrib.get('val') == 'X2':
node.attrib['val'] = x[1]
if node.attrib.get('val') == 'X3':
node.attrib['val'] = x[2]
if node.attrib.get('val') == 'X4':
node.attrib['val'] = x[3]
if node.attrib.get('val') == 'X5':
node.attrib['val'] = x[4]
if node.attrib.get('val') == 'X6':
node.attrib['val'] = x[5]
if node.attrib.get('val') == 'X7':
node.attrib['val'] = x[6] 
XML_File= open('output'+str(count)+'.xml', 'wb') 
tree.write(XML_File)
XML_File.close()

最新更新