title: Parsing an XML file properly for CSV output
body: <p>I've built out this script that is meant to parse an XML file and retrieve the contents of the id, created-date, author-id and comments nodes and print them to a CSV. It's <em>mostly</em> working with one exception...</p>
  
  <p>I'm running into a problem where the script is looping through every id in the XML and printing every comment in the XML as if it were part of that id when it isn't the case.</p>
  
  <p>Ideally, the end goal is to only obtain and print comments that belong to each unique id and print the contents of the comment nodes.</p>
  
  <p>Example of the issue (CSV output):</p>
  
  <pre><code>Ticket ID,Created Date,Author ID,Comment
  992,2016-06-21,232245,"Hi, this is what is happening."
  992,2016-06-22,231122,"This is another comment from the same id."
  996,2016-06-21,232245,"Hi, this is what is happening."
  996,2016-06-22,231122."This is another comment from the same id."
  </code></pre>
  
  <p>I would just like to print comments only associated with id's and not every comment with every id (if that makes any sense).</p>
  
  <p>Here is the code:</p>
  
  <pre><code>#!/usr/bin/env python
  # -*- coding: utf-8 -*-
  
  import os
  import sys
  
  from xml.etree import ElementTree as ET
  import csv
  
  xml_file = sys.argv[1]
  
  if not xml_file.endswith('.xml'):
      print "%s is not a valid XML file. Exiting." % xml_file
      exit()
  
  tree = ET.parse(xml_file)
  root = tree.getroot()
  
  # Ignore characters/string(s) (if any)
  ignore_chars = ['&gt;', '&gt;&gt;']
  
  
  class RotateFile(object):
      def __init__(self, directory='', filename='', max_files=sys.maxint,
                   max_file_size='', header=''):
          self.ii = 1
          self.header = header
          self.directory, self.filename = directory, filename
          self.max_file_size, self.max_files = max_file_size, max_files
          self.finished, self.fh = False, None
          self.open()
  
      def rotate(self):
          """Rotate the file, if necessary"""
          if (os.stat(self.filename_template).st_size &gt; self.max_file_size):
              self.close()
              self.ii += 1
              if (self.ii &lt;= self.max_files):
                  self.open()
              else:
                  self.close()
                  self.finished = True
  
      def open(self):
          self.fh = open(self.filename_template, 'w')
          self.writer = csv.writer(self.fh)
          self.writer.writerow(self.header)
  
      def write(self, text=""):
          self.writer = csv.writer(self.fh)
          self.writer.writerow([s.encode("utf-8") for s in text])
          self.fh.flush()
          self.rotate()
  
      def close(self):
          self.fh.close()
  
      @property
      def filename_template(self):
          return "%0.2d" % self.ii + "_" + self.filename
  
  
  def comments():
      for comment in root.iter('comment'):
          created_at = comment.find("created-at").text
          value = comment.find("value").text
          author_id = comment.find("author-id").text
          if not value:
              continue
          yield created_at, value, author_id
  
  
  def tickets(root):
      for ticket in root.iter('ticket'):
          nice_id = ticket.find("nice-id").text
          for comment in comments():
              created_at, value, author_id = comment
              yield nice_id, created_at, author_id, value
  
  
  # Set arguments
  args = {'directory': '',
          'filename': 'output.csv',
          'max_file_size': 10485760,
          'header': ['Ticket ID', 'Created Date', 'Author ID', 'Comment'],
          }
  
  fout = RotateFile(**args)
  
  for row in tickets(root):
      if not any(ignore_chars in row for ignore_char in ignore_chars):
          print ','.join(row)
          fout.write(row)
  </code></pre>
  
  <p>Much appreciated in advance, all.</p>