0

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'
user3848207
  • 3,737
  • 17
  • 59
  • 104
  • 1
    Possible duplicate of [python 3.5: TypeError: a bytes-like object is required, not 'str' when writing to a file](https://stackoverflow.com/questions/33054527/python-3-5-typeerror-a-bytes-like-object-is-required-not-str-when-writing-t) – Patrick Artner Jul 22 '18 at 08:40
  • Did my solution work ? – Agile_Eagle Jul 22 '18 at 08:48
  • This question has been answered in another question. https://stackoverflow.com/questions/51463449/replace-csv-header-without-deleting-the-other-rows – user3848207 Aug 01 '18 at 12:38

1 Answers1

1

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

Agile_Eagle
  • 1,710
  • 3
  • 13
  • 32
  • It almost worked. I asked another question to address it. Thank you for your answer. Upvoted but I could not marked it as the correct answer. https://stackoverflow.com/questions/51463449/replace-csv-header-without-deleting-the-other-rows – user3848207 Jul 22 '18 at 08:49