1 回答
TA贡献1802条经验 获得超10个赞
试试下面的代码。正如您所说,您希望为目录中的所有 XML 文件重复读取 XML 文件。缺少的是重复读取每个文件。我进一步假设结果应该写入同一个 CSV 文件。此外,我重命名了包含文件名列表的变量。这不是绝对必要的,但最好避免将变量命名为与关键字相同的名称。
import csv
import xml.etree.ElementTree as ET
import os
path = r"C:\\Users\ADMIN\Desktop\prog"
filenames = []
for filename in os.listdir(path):
if not filename.endswith('.xml'):
continue
fullname = os.path.join(path,filename)
print(fullname)
filenames.append(fullname)
csvfile = open('prova.csv','w')
csv_writer = csv.writer(csvfile)
for filename in filenames:
tree = ET.parse(filename)
root = tree.getroot()
PrimoFor=[]
print("Dati Riepilogo per aliquota IVA e natura")
for datir in root.iter('DatiRiepilogo'):
for element in datir:
print(element.tag,element.text)
PrimoFor.append(element.text)
for CedentePrestatore in root.iter('CedentePrestatore'):
for TagFiglioCedentePrestatore in CedentePrestatore:
for TagNipoteCedentePrestatore in TagFiglioCedentePrestatore:
for ProNipoteCedentePrestatore in TagNipoteCedentePrestatore:
print(ProNipoteCedentePrestatore.tag,ProNipoteCedentePrestatore.text)
PrimoFor.append(ProNipoteCedentePrestatore.text)
for DatiGeneraliDocumento in root.iter('DatiGeneraliDocumento'):
for FiglioDatiGeneraliDocumento in DatiGeneraliDocumento:
if(FiglioDatiGeneraliDocumento.tag!='Divisa'):
print(FiglioDatiGeneraliDocumento.tag,FiglioDatiGeneraliDocumento.text)
PrimoFor.append(FiglioDatiGeneraliDocumento.text)
for DatiPagamento in root.iter('DatiPagamento'):
for TagFiglioDatiPagamento in DatiPagamento:
for TagNipoteDatiPagamento in TagFiglioDatiPagamento:
if(TagNipoteDatiPagamento.tag=='ModalitaPagamento'):
print(TagNipoteDatiPagamento.tag,TagNipoteDatiPagamento.text)
PrimoFor.append(TagNipoteDatiPagamento.text)
csv_writer.writerow(PrimoFor)
#closecsv
csvfile.close()
添加回答
举报
