Return to Snippet

Revision: 48376
at June 30, 2011 01:23 by eristoddle


Initial Code
import csv
 
def fix_name(n):
  'Fixes a string to be nicer (usable) variable names.'
  return n.replace(' ','_').replace('.','_')
 
def read_csv(inf, close_file=True):
  'Reads a csv file in as a list of objects'
  def from_csv_line(l, h):
    return DictObj(dict(zip(h, l)))
  iter = csv.reader(inf).__iter__()
  header = map(fix_name, iter.next())
  for i in iter:
    yield from_csv_line(i, header) 
  if close_file:
    inf.close()
 
def write_csv(out, objs, cols=None, close_file=True):
  'Writes a list of dicts out as a csv file.'
  def to_csv_line(obj, header):
    def lookup_or_empty(o, k, default=''):
      if k in o:
        return o[k]
      return default
    return map(lambda h : lookup_or_empty(obj,h), header)
  iter = objs.__iter__()
  output = csv.writer(out)
  first = iter.next()
  if cols is None:
    cols = sorted(first.keys())
  output.writerow(cols)
  output.writerow(to_csv_line(first, cols))
  output.writerows(map(lambda x: to_csv_line(x, cols), iter))
  if close_file:
    out.close()

Initial URL

                                

Initial Description

                                

Initial Title
Python CSV Row to Object

Initial Tags
python, csv

Initial Language
Python