npm
npm

Reputation: 653

How to parse several XML file into several CSV file?

I parsed XML file using this code that works for a single xml input to single csv output. I tried using glob to work on several input and also several csv output but I know this is not correct.

import glob
import xml.etree.ElementTree as et
import csv

for file in glob.glob('./*.xml'):
    with open(file) as f:
        tree = et.parse(f)
        nodes = tree.getroot()

        with open(f'{f[:-4]}edited.csv', 'w') as ff:
            cols = ['dateTime','x','y','z','motion','isMoving','stepCount','groupAreaId','commit']
            nodewriter = csv.writer(ff)
            nodewriter.writerow(cols)
            for node in nodes:
                values = [ node.attrib.get(kk, '') for kk in cols]
                nodewriter.writerow(values)

How should I change to get several csv output?

Upvotes: 3

Views: 89

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

Your code is currently using a file handle to form your output filename. Instead of f use file as follows:

import glob
import xml.etree.ElementTree as et
import csv

for file in glob.glob('./*.xml'):
    with open(file) as f:
        tree = et.parse(f)
        nodes = tree.getroot()

        with open(f'{file[:-4]}edited.csv', 'w') as ff:
            cols = ['dateTime','x','y','z','motion','isMoving','stepCount','groupAreaId','commit']
            nodewriter = csv.writer(ff)
            nodewriter.writerow(cols)
            for node in nodes:
                values = [ node.attrib.get(kk, '') for kk in cols]
                nodewriter.writerow(values)

Upvotes: 1

SM Abu Taher Asif
SM Abu Taher Asif

Reputation: 2331

you can create a list of file names then write xml files there. If output files ar already in the derectory then using glob you can get names. If the files is not exist the below code will create using given file name

csvFileNames = ['outputfile1.csv', 'outputfile2.csv']
for file in csvFileNames:
    with open(file, 'w') as f:
        wtr = csv.writer(f)
        wtr.writerows( [[1, 2], [2, 3], [4, 5]]) # write what you want

to get XML filenames from directory you can try below code :

from os import listdir
filenames = listdir('.') # here dot is used because script and csv files are in the same directory, if XML files are in other directory then set the path inside listdir
xmlFileNames = [ filename for filename in filenames if filename.endswith( ".xml" ) ]

# get xml file names like this, xmlFileNames = ["abc.xml", "ef.xml"]
resultCsvFileNameList = [fname.replace(".xml", ".csv") for fname in xmlFileNames ]

Upvotes: 0

Related Questions