fork download
  1. #!/usr/bin/env python2.7
  2. # -*- coding: utf-8 -*-
  3.  
  4.  
  5. def convert(src, dst):
  6. import csv
  7. from itertools import chain, izip_longest
  8. # NOTE: see also document itertools recipe "grouper" function.
  9. # NOTE: python3 built-in "zip" returns an iterator object
  10.  
  11. parse = lambda x: x.strip().split(" ")
  12. output = csv.writer(dst).writerow
  13.  
  14. for e in izip_longest(*[iter(src)]*2):
  15. output(list(chain(*map(parse,e))))
  16.  
  17.  
  18. if __name__ == "__main__":
  19.  
  20. if 0:
  21. with open("data.dat") as src, open("out.csv","w") as dst:
  22. convert(src, dst)
  23.  
  24. if 1: # for ideone.com
  25. import sys
  26. convert(sys.stdin, sys.stdout)
Success #stdin #stdout 0.01s 7904KB
stdin
0001 abcde 123 456
789 111 111
0002 fghij 012 345
000 000 000
stdout
0001,abcde,123,456,789,111,111
0002,fghij,012,345,000,000,000