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

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

(CSV) TypeError: a bytes-like object is required, not 'str' #

To solve the Python csv "TypeError: a bytes-like object is required, not 'str'", make sure to open the CSV file in w mode and not wb and use the io.StringIO class instead of io.BytesIO if working with streams.

csv bytes like object is required not str

Here is an example of how the error occurs.

main.py
import csv # 👇️ note file is open in wb mode with open('example.csv', 'wb') as csvfile: csv_writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) # ⛔️ TypeError: a bytes-like object is required, not 'str' csv_writer.writerow(['Alice', 'Bob', 'Carl'])

We opened the file in wb (binary) mode rather than w (text) mode which caused the error.

To solve the error, use the w mode when writing to a CSV file.

main.py
import csv # ✅ make sure to set mode to `w` and set newline kwarg with open('example.csv', 'w', newline='') as csvfile: csv_writer = csv.writer(csvfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['Alice', 'Bob', 'Carl'])
We set the mode to w (text) and set the newline keyword argument to an empty string, which is mandatory when working with CSV files in Python 3.

If newline='' is not specified, newlines embedded inside quoted fields are not interpreted correctly.

For example, on platforms that use \r\n line endings on write, an extra \r will be added unless newline='' is specified.

If you are writing to an io.BytesIO object, use the io.StringIO class instead as the csv writer only handles strings.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.