该程序基本上会展平 xml 文件并将其写入 csv。
我的问题是“values_loop”中的“row”变量在调用之间不会重置。每次我调用它时,新值都会附加到旧值上。
基本上我得到了这个:
A B C
A B C D E F
A B C D E F G H I
什么时候我应该得到这个
A B C
D E F
G H I
我的代码:
import csv
import xml.etree.ElementTree as ET
file_name = '2.xml'
root = ET.ElementTree(file=file_name).getroot()
csv_file_name = '.'.join(file_name.split('.')[:-1]) + ".txt"
print csv_file_name
with open(csv_file_name, 'w') as file_:
writer = csv.writer(file_, delimiter="\t")
def header_loop(root, i=0, row=[]):
for child in root:
#print "\t"*i, child.tag.replace("{http://www.tes.com/aps/response}",""), child.attrib, i
row.extend([child.tag.replace("{http://www.tes.com/aps/response}","")])
header_loop(child,i+1)
if i==0: return row
def values_loop(root, i=0, row=[]):
for child in root:
#print "\t"*i, child.tag.replace("{http://www.tes.com/aps/response}",""), child.attrib, i
row.extend([child.text])
#print child.text
values_loop(child,i+1)
if i==0: return row
#write the header
writer.writerow(header_loop(root[3]))
#write the values
writer.writerow(values_loop(root[3]))
writer.writerow(values_loop(root[4]))
最佳答案
将“无”设置为行的默认值。
def values_loop(root, i=0, row=None):
if row == None:
row = []
关于python - 变量在函数调用之间不清除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23640630/