How Convert Multiple Xml Files in a Folder in Csv Files with Python?

How Convert Multiple Xml Files in a Folder in Csv Files with Python?

1-I ready have a code than convert de xml file to csv. But actually I need to do this operation a lot times and then a need to change the name of the xml file in my program each time.I want to do a loop to read each '.xml' file in the folder location and do for all file. there is my original code

import xml.etree.ElementTree as ET
import csv

tree = ET.parse("Shot_30AA.xml")
root = tree.getroot()

Shot_30AA = open('Shot_30AA.csv', 'w', newline='')
csvwriter = csv.writer(Shot_30AA)
head = []

ShotCode = root.attrib['ShotCode']
csvwriter.writerow(['ShotCode', ShotCode])
head.append(ShotCode)

for member in root.getchildren():
  submembers = member.getchildren()
  keys = submembers[0].attrib.keys()
  csvwriter.writerow ("\n")
  csvwriter.writerow(keys)
  for submember in submembers:
    row_data = [submember.attrib[k] for k in keys]
    csvwriter.writerow(row_data )
Shot_30AA.close()

I tried to do this operation in my file folder adding the fallowing code to do only one time

path = 'C:/Users/Desktop/Program'
for filename in os.listdir(path):
   if not filename.endswith('.xml'): continue
     ShotFile = os.path.join(path, filename)
     tree = ET.parse(ShotFile)
     root = tree.getroot()

     filename = open( filename'.csv', 'w', newline='')
     csvwriter = csv.writer(filename)
     head = [] 

     ShotFile = open('ShotFile.csv', 'w', newline='')
     csvwriter = csv.writer(Shot_30AA)
     head = []

     ShotCode = root.attrib['ShotCode']
     csvwriter.writerow(['ShotCode', ShotCode])
     head.append(ShotCode)

     for member in root.getchildren():
       submembers = member.getchildren()
       keys = submembers[0].attrib.keys()
       csvwriter.writerow ("\n")
       csvwriter.writerow(keys)
       for submember in submembers:
         row_data = [submember.attrib[k] for k in keys]
         csvwriter.writerow(row_data )
  ShotFile.close()

I expect to obtain all my files in csv format with one run.

1 Answer

Here's what could work based on your code

def make_csv(folderpath, xmlfilename):
    tree = ET.parse(os.path.join(folderpath, xmlfilename))
    root = tree.getroot()
    filename, _ = xmlfilename.rsplit('.', 1)
    Shot_30AA = open(filename+'.csv', 'w', newline='')
    csvwriter = csv.writer(Shot_30AA)
    head = []

    ShotCode = root.attrib['ShotCode']
    csvwriter.writerow(['ShotCode', ShotCode])
    head.append(ShotCode)

    for member in root.getchildren():
        submembers = member.getchildren()
        keys = submembers[0].attrib.keys()
        csvwriter.writerow("\n")
        csvwriter.writerow(keys)
        for submember in submembers:
            row_data = [submember.attrib[k] for k in keys]
            csvwriter.writerow(row_data)
    Shot_30AA.close()

path = 'C:/Users/Desktop/Program'
for filename in os.listdir(path):
    if filename.endswith('.xml'):
        make_csv(path, filename)

EDIT 1: As the comments pointed out, you should also take a look at the with open() as clause when dealing with files

2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.