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

2019-04-08 22:20发布

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.

3条回答
ら.Afraid
2楼-- · 2019-04-08 23:01

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()    
查看更多
再贱就再见
3楼-- · 2019-04-08 23:05

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.

查看更多
放我归山
4楼-- · 2019-04-08 23:07

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

查看更多
登录 后发表回答