python - 变量在函数调用之间不清除

标签 python xml csv

该程序基本上会展平 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/

相关文章:

python - 多级图像阈值

java - 实现 ScrollView 导致致命异常

java - 使用属性文件进行 Spring XML 配置的可选参数

excel - CSV 文件/Excel 中的日期/时间格式

python - 如何在 python 中更改 iBus 输入法?

python - Pygame 的 colliderect 没有注意到碰撞

ios - 使用钛创建 XML 文档

mongodb - mongoimport 导入csv文件乱序

ruby-on-rails - Paginate 使用逗号 gem 限制我的 csv 导出 - 如何解决?

python - 如何在pyqt(QGIS)中捕捉QDockWidget的KeyPressedEvent