python-变量未清除中间函数调用

python-变量未清除中间函数调用,python,xml,csv,Python,Xml,Csv,这个程序基本上是将xml文件展平并写入csv 我的问题是“values\u 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'

这个程序基本上是将xml文件展平并写入csv

我的问题是“values\u 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 = []

永远不要将可变项(列表、字典)用作默认参数。这会中断递归。谢谢,通过在递归调用中传递行来实现这一点。对不起,我应该注意到,您必须在递归调用中传递行。很高兴你成功了!