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

advertisements

I want to write data that I have to create a histogram into a csv file. I have my 'bins' list and I have my 'frequencies' list. Can someone give me some help to write them into a csv in their respective columns?

ie bins in the first column and frequency in the second column


This example uses izip (instead of zip) to avoid creating a new list and having to keep it in the memory. It also makes use of Python's built in csv module, which ensures proper escaping. As an added bonus it also avoids using 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))