如何使用Python将元组的元组写入CSV文件 [英] How to write a tuple of tuples to a CSV file using Python
本文介绍了如何使用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)
这篇关于如何使用Python将元组的元组写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文