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

2024-04-20 09:54:50 发布

您现在位置:Python中文网/ 问答频道 /正文

这个程序基本上是将一个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]))

Tags: csvnameloopchildhttptagrootxml