0

I tried the below code to write a list to csv file, but it always shows the error:

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

Below is the code:

import csv
a=['a','b','c']
with open(r"result.csv",'wb') as resultFile:
    writer = csv.writer(resultFile, lineterminator='\n')
    for i in a:
        writer.writerows([[i]])
  • 1
    Possible duplicate of [TypeError: a bytes-like object is required, not 'str' in python and CSV](https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv) – Rahul Mar 08 '18 at 08:05

2 Answers2

4

you open your file in 'binary' mode instead of 'text' mode:

with open(r"result.csv",'w') as resultFile:  # instead of 'wb'

should work.

hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
  • what is the difference between "w" and "wb" –  Mar 08 '18 at 08:02
  • [`open`](https://docs.python.org/3/library/functions.html#open) in my answer is a link to the documentation; also this may help: https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files – hiro protagonist Mar 08 '18 at 08:03
  • 1
    Don't answer duplicate question. This is exact duplicate of : https://stackoverflow.com/questions/34283178/typeerror-a-bytes-like-object-is-required-not-str-in-python-and-csv – Rahul Mar 08 '18 at 08:28
0

Like @hiro protagonist said, you are opening the file in binary mode. Here is some helpful documentation.

Python distinguishes between binary and text I/O. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.

You could also use pandas to_csv:

import pandas as pd

a = ['a', 'b', 'c']
df = pd.DataFrame(a)
df.to_csv('result.csv', header=None, index=False)
srikavineehari
  • 2,502
  • 1
  • 11
  • 21