如何使用Python将元组的元组写入CSV文件

问题描述:

我有一个元组的元组

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

这将用A [0],A [1]和A [2]的行写一个CSV文件。
我想要的是一个名称,年龄和性别的行,它们具有相应的值。

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 .

writer.writerows(A)

而不是

writer.writerow(A)

文件newfile.csv看起来像这样:

File newfile.csv looks now like this:

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

此外,添加()到最后一行,它是一个函数调用: result.close()

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

如果您使用Python 2.6或更高版本,可以使用以下格式:

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)