【问题标题】:How to use python csv write the title first then write the content?如何使用python csv先写标题再写内容?
【发布时间】:2018-11-15 14:30:16
【问题描述】:

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

名单:

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

标题:

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

我想要这个结果:

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

我的代码:

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)

如何修改?

【问题讨论】:

    标签: python python-3.x csv


    【解决方案1】:

    现在我知道该怎么做了。

    第一次使用:

    writer.writerows(title)

    然后使用:

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-02-12
      • 2015-04-04
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多