How to write data from two lists to columns in csv?

I want to write the data that I have to create a histogram in a csv file. I have a list of baskets and I have a list of frequencies. Can someone help me write them in csv in the appropriate columns?

i.e. cells in the first column and frequency in the second column

+7
python file-io csv
source share
3 answers

This example uses izip (instead of zip ) to avoid creating a new list and storing it in memory. It also uses Python, built into the csv module , which provides proper escaping. As an added bonus, it also avoids the use of any loops, so the code is short and concise.

 import csv from itertools import izip with open('some.csv', 'wb') as f: writer = csv.writer(f) writer.writerows(izip(bins, frequencies)) 
+12
source share

Hmm, am I missing something? It sounds pretty simple:

 bins = [ 1,2,3,4,5 ] freq = [ 9,8,7,6,5 ] f = open("test.csv", "w") for i in xrange(len(bins)): f.write("{} {}\n".format(bins[i], freq[i])) f.close() 
+3
source share

you should use zip () http://docs.python.org/2/library/functions.html#zip

something like:

 f=open(my_filename,'w') for i,j in zip(bins,frequencies): f.write(str(i)+","+str(j)) f.close() 
+2
source share