Sunday, 2 June 2013

Transferring CSV data into different Functions in Python

Transferring CSV data into different Functions in Python

i need some help. Basically, i have to create a function to read a csv file then i have to transfer this data into another function to use the data to generate a xml file. Here is my code:
  import csv
  from xml.etree.ElementTree import Element, SubElement, Comment, tostring
  from xml.etree.ElementTree import ElementTree
  import xml.etree.ElementTree as etree

  def read_csv():
      with open ('1250_12.csv', 'r') as data:
           reader = csv.reader(data)
      return reader

  def generate_xml(reader):
      root = Element('Solution')
      root.set('version','1.0')
      tree = ElementTree(root)

      head = SubElement(root, 'DrillHoles')
      head.set('total_holes', '238')

      description = SubElement(head,'description')
      current_group = None
      i = 0
      for row in reader:
          if i > 0:
             x1,y1,z1,x2,y2,z2,cost = row
             if current_group is None or i != current_group.text:
                  current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                  information = SubElement (current_group, 'hole',{'collar':', '.join((x1,y1,z1)),
                                                     'toe':', '.join((x2,y2,z2)),
                                                     'cost':    cost})
          i+=1

    def main():
        reader = read_csv()
        generate_xml(reader)

        if __name__=='__main__': main()
but i get an error when i try to pass reader, the error is: ValueError: I/O operation on closed file

No comments:

Post a Comment