5

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.

psoares
  • 4,733
  • 7
  • 41
  • 55
Corey
  • 405
  • 2
  • 9
  • 18
  • 2
    Can you just make a comma or tab delimited file and then open it in excel? – mrK May 31 '11 at 16:29
  • Please correct the code formatting. All the needed explanation about formatting can be found on the editing page. There's even a preview window below the editing field. – viraptor May 31 '11 at 16:29

3 Answers3

6

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()    
psoares
  • 4,733
  • 7
  • 41
  • 55
  • thank you very much, this will be extremely helpful! I had originally searched the forums for a way to do this with xlwt but this will work just fine. thanks again! – Corey May 31 '11 at 17:42
  • I do the same with an array, so if you have any doubt, just ask ;) – psoares May 31 '11 at 17:43
4

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

Corey Ogburn
  • 24,072
  • 31
  • 113
  • 188
2

The built-in solution is python's csv module. You can create a csv.writer and use that to append rows to a .csv file, which can be opened in excel.

senderle
  • 145,869
  • 36
  • 209
  • 233
  • Thank you! It is working well and will be a helpful tool in producing some useful visuals! – Corey May 31 '11 at 17:53