简体   繁体   中英

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

I have a list of strings in 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;

column_1, column_2, column_3

I am using 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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