I have a number of csv files which have variable length rows. For example The following:
Time,0,8,18,46,132,163,224,238,267,303
X,0,14,14,14,15,16,17,15,15,15
Time,0,4,13,22,32,41,50,59,69,78,87,97,106,115,125,127,137,146,155,165,174,183,192,202,211,220,230,239,248,258,267,277,289,298,308
Y,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
Time,0,4,13,22,32,41,50,59,69,78,87,97,106,115,125,127,137,146,155,165,174,183,192,202,211,220,230,239,248,258,267,277,289,298,308
Z,0,1,2,1,1,1,1,1,1,2,2,1,0,1,1,2,2,2,2,2,1,1,2,2,2,1,1,1,1,1,2,2,2,2,2
Time,0,308
W,0,0
Becomes:
Time,X,Time,Y,Time,Z,Time,W
0,0,0,0,0,0,0,0
8,14,4,0,4,1,308,0
A lot of data has been lost, it only took the first 2 of each.
I want to transpose this CSV in python. I have the following program:
import csv
import os
from itertools import izip
import sys
try:
filename = sys.argv[1]
except IndexError:
print 'Please add a filename'
exit(-1)
with open(os.path.splitext(filename)[0] + '_t.csv', 'wb') as outfile, open(filename, 'rb') as infile:
a = izip(*csv.reader(infile))
csv.writer(outfile).writerows(a)
However it seems to trim a lot of data because the file has dropped from 20KB to 6KB and only keeps up to the minimum row length.
Any ideas how to not drop any data?