如何使用 Python 将元组的元组写入 CSV 文件 [英] How to write a tuple of tuples to a CSV file using Python

查看:54
本文介绍了如何使用 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

这会写入一个 CSV 文件,其中包含 A[0]、A[1] 和 A[2] 的行.我想要的是一个有姓名、年龄和性别的行,它有相应的值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆