Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: CSV write by column rather than row

Tags:

python

csv

I have a python script that generates a bunch of data in a while loop. I need to write this data to a CSV file, so it writes by column rather than row.

For example in loop 1 of my script I generate:

(1, 2, 3, 4) 

I need this to reflect in my csv script like so:

Result_1    1 Result_2    2 Result_3    3 Result_4    4 

On my second loop i generate:

(5, 6, 7, 8) 

I need this to look in my csv file like so:

Result_1    1    5 Result_2    2    6 Result_3    3    7 Result_4    4    8 

and so forth until the while loop finishes. Can anybody help me?


EDIT

The while loop can last over 100,000 loops

like image 730
Harpal Avatar asked Nov 11 '10 13:11

Harpal


2 Answers

The reason csv doesn't support that is because variable-length lines are not really supported on most filesystems. What you should do instead is collect all the data in lists, then call zip() on them to transpose them after.

>>> l = [('Result_1', 'Result_2', 'Result_3', 'Result_4'), (1, 2, 3, 4), (5, 6, 7, 8)] >>> zip(*l) [('Result_1', 1, 5), ('Result_2', 2, 6), ('Result_3', 3, 7), ('Result_4', 4, 8)] 
like image 159
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 10:10

Ignacio Vazquez-Abrams


wr.writerow(item)  #column by column wr.writerows(item) #row by row 

This is quite simple if your goal is just to write the output column by column.

If your item is a list:

yourList = []  with open('yourNewFileName.csv', 'w', ) as myfile:     wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)     for word in yourList:         wr.writerow([word]) 
like image 25
the curious mind Avatar answered Oct 11 '22 09:10

the curious mind