Python CSV Row to Object


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. import csv
  2.  
  3. def fix_name(n):
  4. 'Fixes a string to be nicer (usable) variable names.'
  5. return n.replace(' ','_').replace('.','_')
  6.  
  7. def read_csv(inf, close_file=True):
  8. 'Reads a csv file in as a list of objects'
  9. def from_csv_line(l, h):
  10. return DictObj(dict(zip(h, l)))
  11. iter = csv.reader(inf).__iter__()
  12. header = map(fix_name, iter.next())
  13. for i in iter:
  14. yield from_csv_line(i, header)
  15. if close_file:
  16. inf.close()
  17.  
  18. def write_csv(out, objs, cols=None, close_file=True):
  19. 'Writes a list of dicts out as a csv file.'
  20. def to_csv_line(obj, header):
  21. def lookup_or_empty(o, k, default=''):
  22. if k in o:
  23. return o[k]
  24. return default
  25. return map(lambda h : lookup_or_empty(obj,h), header)
  26. iter = objs.__iter__()
  27. output = csv.writer(out)
  28. first = iter.next()
  29. if cols is None:
  30. cols = sorted(first.keys())
  31. output.writerow(cols)
  32. output.writerow(to_csv_line(first, cols))
  33. output.writerows(map(lambda x: to_csv_line(x, cols), iter))
  34. if close_file:
  35. out.close()

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.