使用字符串列表用逗号定界符写入csv文件的标头

时间:2018-07-22 08:14:27

标签: python python-3.x csv

我在python中有一个字符串列表。

header_list = ['column_1', 'column_2', 'column_3']

我想基于text.csv替换cvs文件header_list的标题行,以使标题看起来像这样;

column_1, column_2, column_3

我正在使用python v3.6

编辑:这是我想出的代码。

import csv
with open('text.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow(header_list)

我得到了错误;

TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:1)

您正在以字节模式打开文件。而是以常规写入模式打开它,如下所示:

with open('text.csv', 'a') as csvfile:

这将使您可以在csv中写入流对象