简体   繁体   English

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

[英]Write to header of csv file with comma delimiter using list of strings

I have a list of strings in python. 我在python中有一个字符串列表。

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

I want to replace the header row of a cvs file text.csv based on header_list such that the header will look like this; 我想基于header_list替换cvs文件text.csv的标题行,以便标题看起来像这样;

column_1, column_2, column_3

I am using python v3.6 我正在使用python v3.6

EDIT: Here is the code that I came up with. 编辑:这是我想出的代码。

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

I get the error; 我得到了错误;

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

You are opening the file in byte mode. 您正在以字节模式打开文件。 Instead open it in normal write mode like this: 而是以常规写入模式打开它,如下所示:

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

This will let you write stream objects in the csv 这将使您可以在csv中写入流对象

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

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