Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 817
Corey Avatar asked May 31 '11 16:05

Corey


2 Answers

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()    
like image 108
psoares Avatar answered Oct 05 '22 22:10

psoares


A great file type to be aware of is a CSV, or Comma Separated Value file. It's a very simple text file type (normally already associated with Excel or other spreadsheet apps) where each comma separates multiple cells on the same row and each new line in the file represents data on a new row. I.E.:

A,B,C
1,2,3
"Hello, World!"

The above example would result in the first row having 3 cells, each cell holding each letter. The new line states that 1, 2, and 3 are in the next row, each in their own cell. If a cell needs a comma in it, you can place that cell in quotes. In my example, "Hello, World!" would exist in the 3rd row, 1st cell. For a more formal definition: http://www.csvreader.com/csv_format.php

like image 32
Corey Ogburn Avatar answered Oct 05 '22 22:10

Corey Ogburn