【问题标题】:including headers when writing a csv python3在编写 csv python3 时包括标题
【发布时间】:2018-04-25 02:33:11
【问题描述】:

我习惯以这种特殊方式写出CSV,但我 我不知道如何包含标题,因为大多数示例都不是这种格式。

ff = open('data.csv','w')

# Included here would be a typical for loop creating the below variables, i, list_name[i], list_date[i]

ff.write( "%7d, %s, %s\n" % (i, list_name[i], list_date[i]))

【问题讨论】:

  • 嗨,欢迎来到 Stackoverflow,您可以使用 code formatting 来实际突出显示您的代码。您可以使用 4 spaces 缩进您的代码行,以便它正确呈现并且其他用户知道您的代码到底在哪里。

标签: python-3.x


【解决方案1】:

您可能想使用csv 包,这里是一个示例:

import csv

myData = [["first_name", "second_name", "Grade"],
      ['Alex', 'Brian', 'A'],
      ['Tom', 'Smith', 'B']]

myFile = open('file.csv', 'w')
with myFile:
    writer = csv.writer(myFile)
    writer.writerows(myData)

print("done")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-04
    • 2019-04-07
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-24
    相关资源
    最近更新 更多