ASH
ASH

Reputation: 20302

Loop and write to a CSV file?

I am trying to loop through a XML file, and parse out the elements that I need. I can print to the console window just fine, but the results are too large, and fill the entire console before before it ends. So, I am trying to dump everything to a CSV file. Now, it seems like I get only one single character per row in the CSV when the script finishes. My code must be close, but obviously something is wrong.

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('C:\\path\\Recon.xml')
root = tree.getroot()

with open('C:\\path\\data.csv', 'w') as f:

    for neighbor in root.iter('inputColumn'):
        print(neighbor.attrib)
        writer = csv.writer(f)
        writer.writerows(neighbor.attrib)

I am using 3.6.3!

Just posting the final version of my code here....

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('C:\\path\\Recon.xml')
root = tree.getroot()

with open('C:\\path\\data.csv', 'w') as f:
    writer = csv.writer(f)
    for neighbor in root.iter('inputColumn'):
        print(neighbor.attrib)
        writer.writerow(neighbor.attrib)

This is so, so, so simple. After working with Python for a few years, and (basically) hating it, I am really starting to love it now!!

Upvotes: 1

Views: 108

Answers (1)

ak_slick
ak_slick

Reputation: 1016

Answer to reflect comments above for ease of future reference.

import xml.etree.ElementTree as ET
import csv

tree = ET.parse('C:\\path\\Recon.xml')
root = tree.getroot()

with open('C:\\path\\data.csv', 'w') as f:

    writer = csv.writer(f)

    for neighbor in root.iter('inputColumn'):
        print(neighbor.attrib)
        writer.writerow(neighbor.attrib)

Upvotes: 1

Related Questions