5

I have a tuple of tuples

import csv
A = (('Max', 3 ,' M'),('bob',5,'M'),('jane',6,'F'))
result = open("newfile.csv",'wb')
writer = csv.writer(result, dialect = 'excel')
writer.writerow(A)
result.close

This writes a CSV file with rows with A[0], A[1] and A[2] . What i want is a row with name, age and gender , which has the corresponding values .

John Machin
  • 81,303
  • 11
  • 141
  • 189
Viv_bio
  • 99
  • 1
  • 7
  • you want one row with 3 columns, each for name, age and gender, and you're getting one column with all three inside? – milan Dec 31 '11 at 10:31

2 Answers2

11

Write all rows at once:

writer.writerows(A)

instead of

writer.writerow(A)

File newfile.csv looks now like this:

Max,3, M
bob,5,M
jane,6,F

Also, add () to your last line, it is a function call: result.close().

If you are on Python 2.6 or newer, you can use this form:

import csv
A = (('Max', 3, 'M'),('bob', 5, 'M'),('jane', 6, 'F'))
with open('newfile.csv', 'wb') as result:
    writer = csv.writer(result, dialect='excel')
    writer.writerows(A)
eumiro
  • 207,213
  • 34
  • 299
  • 261
  • Equivalently, `for row in A: writer.writerow(A)`. But since you're constructing `A` upfront you might as well use `writerows`. – Katriel Dec 31 '11 at 10:41
  • +1 I was doing it like `csv.writer(f).writerows([x for x in a])` I'm off to rtfm :-) – T I Dec 31 '11 at 10:45
0

Not sure if I understand you fully but I think this will help :

    print >>f, "\n".join([",".join(x) for x in A]);
prongs
  • 9,422
  • 21
  • 67
  • 105