简体   繁体   English

如何将元组列表写入CSV文件?

[英]How to write list of tuple into CSV file?

data=[('name', 'sex', 'date'), ('x1', 'f', '1948/05/28'), ('x2', 'm', '1952/03/27'),\
        ('x3', 'f', '1994/12/09'), ('x4', 'f', '1969/08/02')]
with open("g:\\test","w")  as f:
    writer=csv.writer(f)
    writer.writerow(data)

When i open g:\\test file ,the format is当我打开 g:\\test 文件时,格式是

在此处输入图片说明

How can i write the data into the following format?如何将数据写入以下格式?

在此处输入图片说明

import csv 

data=[('name', 'sex', 'date'), ('x1', 'f', '1948/05/28'), ('x2', 'm', '1952/03/27'),\
        ('x3', 'f', '1994/12/09'), ('x4', 'f', '1969/08/02')]
with open("g:\\test","w")  as f:
    writer=csv.writer(f, delimiter=", ", lineterminator="\r\n") 
    writer.writerows(data)

Spot "s" at the end of writerows .writerows末尾writerows “s”。 Also, see delimiter and lineterminator arguments.另请参阅分隔符和换行符参数。

More examples here .更多例子在这里

To be frank, I can't get what your problem is - values above are default, so your format should be OK...坦率地说,我不明白你的问题是什么——上面的值是默认值,所以你的格式应该没问题......

writer.writerow writes a single line. writer.writerow 写一行。 Multiple lines are written with writer.writerows.多行是用 writer.writerows 编写的。 This is given in the docs .这在文档中给出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM