Alex McLean
Alex McLean

Reputation: 2784

Python csv writer: write a string in front of an array, all in individual columns

Given the following data:

names = ['a','b','c','d']
matrix = [array[1,2,3,4],array[5,6,7,8],array[9,10,11,12],array[13,14,15,16]]

I am trying to print one name in front of each array on a csv file, like so:

Desired Output:

'a',1,2,3,4
'b',5,6,7,8
etc...

So far, I have this code:

with open('test.csv', 'a') as csvfile:
     writer = csv.writer(csvfile, dialect='excel')
     counter = 0
     if matrix.any():
          writer.writerow([names[counter]],[e for e in i])
          counter += 1

This gives me the undesired output of:

['a'],[1,2,3,4]
['b'],[5,6,7,8]

How can I get each item of the array in it's own column, while still having the name at the front?

Upvotes: 0

Views: 790

Answers (3)

Biswanath
Biswanath

Reputation: 9185

Use this

for name, row in zip(names, matrix):
    writer.writerow([name] + row)

Upvotes: 1

Damian Yerrick
Damian Yerrick

Reputation: 4664

Think of what you want each row to look like, then build that row. In this case, you want the row to start with one element of names and have the elements of the corresponding element of matrix appended to it. Use zip() to combine the two sequences into one, then form each row as follows:

#!/usr/bin/env python
import csv

names = ['a','b','c','d']
matrix = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]

with open('test.csv', 'a') as csvfile:
    writer = csv.writer(csvfile, dialect='excel')
    for name, matrix_row in zip(names, matrix):
        output_row = [name]
        output_row.extend(matrix_row)
        writer.writerow(output_row)

The output of this program:

a,1,2,3,4
b,5,6,7,8
c,9,10,11,12
d,13,14,15,16

Upvotes: 3

Blair
Blair

Reputation: 6693

You could try using itertools.chain. Here is a bit of sample code:

>>> import itertools
>>> i = itertools.chain(['a'],[1,2,3,4])
>>> [a for a in i]
['a', 1, 2, 3, 4]

If you just passed the iterator created by chain to the writerow function, you should get your desired result.

Upvotes: 0

Related Questions