how to write python array (data = []) to excel?

Corey picture Corey · May 31, 2011 · Viewed 23.7k times · Source

I am writing a python program to process .hdf files, I would like to output this data to an excel spreadsheet. I put the data into an array as shown below:

Code:

data = []

for rec in hdfFile[:]:
    data.append(rec)

from here I have created a 2D array with 9 columns and 171 rows.

I am looking for a way to iterate through this array and write each entry in order to a sheet. I am wondering if If I should create a list instead, or how to do this with the array I have created.

Any help would be greatly appreciated.

Answer

psoares picture psoares · May 31, 2011

Just like @senderle said, use csv.writer

a = [[1,2,3],[4,5,6],[7,8,9]]
ar = array(a)

import csv

fl = open('filename.csv', 'w')

writer = csv.writer(fl)
writer.writerow(['label1', 'label2', 'label3']) #if needed
for values in ar:
    writer.writerow(values)

fl.close()