Multiple XML files to CSV files python

Viewed 15

Currently this converts one XML file but providing the file name datainput when run from the folder containing the xml file.

Attempting to sequentally run this on all *.xml files in a specified folder and output each to csv.

from xml.etree import ElementTree
import csv

datainput = ("a18.xml")
csvtag = (".csv")
datainputcsv = (datainput+csvtag)

# MODIFY XML
# Read in the file
with open(datainput, 'r') as file :
filedata = file.read()

# Replace the target string
for r in (('<?xml version="1.0" encoding="UTF-8"?>', ""), (' xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"', "")):
filedata = filedata.replace(*r)

# Write the file out again
with open(datainput, 'w') as file:
file.write(filedata)

# PARSE XML
xml = ElementTree.parse(datainput)

# CREATE CSV FILE
csvfile = open(datainputcsv,'w')
csvfile_writer = csv.writer(csvfile)

# ADD THE HEADER TO CSV FILE
csvfile_writer.writerow(["url"])

# FOR EACH EMPLOYEE
for employee in xml.findall("url"):

if(employee):
   
   # EXTRACT EMPLOYEE DETAILS  
  name = employee.find("loc")

  csv_line = [name.text]

  # ADD A NEW ROW TO CSV FILE
  csvfile_writer.writerow(csv_line)
csvfile.close()  
0 Answers
Related