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 .

1
  • you want one row with 3 columns, each for name, age and gender, and you're getting one column with all three inside? Commented Dec 31, 2011 at 10:31

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Equivalently, for row in A: writer.writerow(A). But since you're constructing A upfront you might as well use writerows.
+1 I was doing it like csv.writer(f).writerows([x for x in a]) I'm off to rtfm :-)
0

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

    print >>f, "\n".join([",".join(x) for x in A]);

4 Comments

Profit from the csv, don't reinvent the wheel with this construct (imagine one field being "Max,Happy" would break your CSV file)
Is csv pre-installed with python?
it belongs to the Python Standard Library docs.python.org/library/fileformats.html
CSV is inbuilt in Python 2.3 onwards

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.