2012-08-23 3 views
0

나는 너희들에게 약간의 도움이 필요하다.특정 폴더에서 여러 개의 XML 파일 읽기 - Python

프로그래밍에 익숙하지 않으므로 코드에서 많이 기대하지 않아야합니다.

여기에 문제가 있습니다. XML 파일을 폴더에서 파싱하여 .xls 또는 .csv로 작성해야합니다. 지금까지 xml을 파싱하여 .txt로 작성했지만 필자가 사용하는 파일은 프로그램과 동일한 폴더에 있습니다.

from xml.dom import minidom 

from datetime import * 

ano = int(input("Year: ")) 

mes = int(input("Month: ")) 

dia = int(input("Day: ")) 

dt_obj = datetime(ano, mes, dia) 

date_str = dt_obj.strftime("%Y-%m-%d") 

#Extracting the information from the XML nodes 

xmldoc = minidom.parse("NAME OF THE FILE.XML") 

NFe = xmldoc.getElementsByTagName("NFe")[0] 

infNFe = NFe.getElementsByTagName("infNFe")[0] 

ide = infNFe.getElementsByTagName("ide")[0] 

nNF = ide.getElementsByTagName("nNF")[0].firstChild.data 

dEmi = ide.getElementsByTagName("dEmi")[0].firstChild.data 

serie = ide.getElementsByTagName("serie")[0].firstChild.data 

emit = infNFe.getElementsByTagName("emit")[0] 

cnpj = emit.getElementsByTagName("CNPJ")[0].firstChild.data 

nfeProc = xmldoc.getElementsByTagName("nfeProc")[0] 

chNFe = nfeProc.getElementsByTagName("chNFe")[0].firstChild.data 


try: 

    # This will create a new file or **overwrite an existing file**. 

    f = open(date_str+".txt", "w") 
    try: 
     f.write("CNPJ: "+cnpj) # Write a string to a file 
     f.writelines("\nNUMERO DA NOTA: "+nNF) 
     f.write("\nDATA DE EMISSAO: "+dEmi) 
     f.write("\nSERIE: "+serie) 
     f.write("\nCHAVE ELETRONICA: "+chNFe) 
    finally: 
     f.close() 
except IOError: 
    pass 

나는 그것을 구문 분석, XML을 읽는 성공하고 내가 필요한 노드의 정보를 기록했습니다 : 여기

는 코드입니다. 지금 필요한 것은

은 그들의 무리와 .XLS

사람에 쓰기로 폴더를 읽을 수있다?

+0

HTTP : //www.python -excel.org/는 xls 파일 작업을위한 도구 목록을 제공합니다. 정말로 xls가 필요하거나 csv가합니까? –

+0

해결책을 찾았습니까? 자신을 도운 대답을 표시하거나 자신의 대답을 만드십시오. –

답변

0

크기를 사용해보십시오.

from xml.dom import minidom 
from datetime import * 

ano = int(input("Year: ")) 
mes = int(input("Month: ")) 
dia = int(input("Day: ")) 
dt_obj = datetime(ano, mes, dia) 
date_str = dt_obj.strftime("%Y-%m-%d") 

#Extracting the information from the XML nodes 

def get_files(d): 
     return [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d,f))] 

def parse(files): 
    for xml_file in files: 
     xmldoc = minidom.parse(xml_file) 
     NFe = xmldoc.getElementsByTagName("NFe")[0] 
     infNFe = NFe.getElementsByTagName("infNFe")[0] 
     ide = infNFe.getElementsByTagName("ide")[0] 
     nNF = ide.getElementsByTagName("nNF")[0].firstChild.data 
     dEmi = ide.getElementsByTagName("dEmi")[0].firstChild.data 
     serie = ide.getElementsByTagName("serie")[0].firstChild.data 
     emit = infNFe.getElementsByTagName("emit")[0] 
     cnpj = emit.getElementsByTagName("CNPJ")[0].firstChild.data 
     # now whatever you want... 

parse(get_files(DIRECTORY)) 

DIRECTORY는 XML 파일의 위치입니다.

이것은 코드의 일부일 뿐이므로 나머지는 직접 작성해야합니다. 당신은 당신이 쓰고 싶은 것을 정확하게 제공하지 않았거나 원하는 형식은 CSV 파일 작성하는 데 도움에 ....

뭔가를 쓰기 : XML 파일이있는 경우

# csv_lovation is a location os a *.csv file, and contents is a list of lists: 
# ([ ["row1 item1", "row1 item2", "row1 item3"], ["row2 item1", "row2 item2", "row2 item3"] ]) 
def write_csv(csv_location, contents): 
    with open(csv_location, "w") as file_writer: 
     file_writer.write("Header,Items,Here\n") #if you have no need for a header, remove this line. 
      for line in contents: 
       file_writer.write("%s\n" % ",".join(line)) 
0

을 하나의 폴더, 당신은 같은 작업을 수행 할 수 있습니다

import os 
import sys 

def select_files_in_folder(dir, ext): 
    for file in os.listdir(dir): 
     if file.endswith('.%s' % ext): 
      yield os.path.join(dir, file) 

for file in select_files_in_folder(sys.argv[1], 'xml'): 
    process_xml_file(file) 

또는 파일이 하위 폴더에 사용 될 수있는 경우 :

def select_files_in_subfolders(dir, ext): 
    for root, dirs, files in os.walk(dir): 
     for file in files: 
      if file.endswith('.%s' % ext): 
       yield os.path.join(dir, file)