【发布时间】:2019-08-10 02:21:02
【问题描述】:
我有一个问题,我应该从多个 XML 文件中提取数据并将它们上传到 CSV……当涉及到单个 XML 文件时,我可以提取并加载 CSV 中的数据,但是当它是 XML 文件的目录时,我只能看到名称,但参数传递时没有任何反应。我附上代码,请帮助我。
import csv
import xml.etree.ElementTree as ET
import os
path = r"C:\\Users\ADMIN\Desktop\prog"
string = []
for filename in os.listdir(path):
if not filename.endswith('.xml'):continue
fullname=os.path.join(path,filename)
print(fullname)
string.append(fullname)
tree= ET.parse(fullname)
root = tree.getroot()
csvfile=open('prova.csv','w')
csv_writer = csv.writer(csvfile)
PrimoFor=[]
SecondoFor=[]
TerzoFor=[]
QuartoFor=[]
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()
我也试过这个功能,但没有任何改变
for path , dirs, files in os.walk(path):
for filename in files:
print(filename)
string.append(filename)
提前致谢。 抱歉,语言是谷歌翻译
【问题讨论】:
-
您将目录中所有 XML 文件的完整路径放入名为
string的列表中,但随后您尝试从文件中加载数据,该文件的路径在名为fullname的变量中定义.但是,该变量对于上面的 for 循环是局部的。该变量的值应该被认为是未定义的,python实际上应该警告你。您只想使用第一个(或最后一个)文件吗?或者您想为每个文件重复以下所有代码? -
感谢您的回答。如果我将 {string} 或 {fullname } 放在 {ET.parse() } 下,则没有任何变化。我希望为每个文件重复下面的代码......也就是说,从所有 XML 文件中提取数据
标签: python xml csv xml-parsing