如何使用python csv首先写标题然后写内容?

时间:2018-06-06 02:13:47

标签: python python-3.x csv

我有一个列表,我想将列表写入CSV。但首先,写标题。

列表:

  

top_list = [[1,2,3],[4,5,6],[7,8,9]]

标题:

  

title = [' col1',' col2',' col3']

我想要这个结果:

enter image description here

但是现在,我的代码的结果是:

enter image description here

我的代码:

import csv

top_list = [[1,2,3],[4,5,6],[7,8,9]]
title = ['col1','col2','col3']
with open(r'D:/aaa.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(top_list)

如何修改?

1 个答案:

答案 0 :(得分:0)

现在我知道该怎么做了。

首次使用:

  

writer.writerows(标题)

然后使用:

  

writer.writerows(top_list)

现在代码可以做到:

import csv

top_list = [[1,2,3],[4,5,6],[7,8,9]]
title = ['col1','col2','col3']
with open(r'D:/aaa.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerows(title)
    writer.writerows(top_list)