Last updated: Apr 20, 2022
Photo from Unsplash
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.
Here is an example of how the error occurs.
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.
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'])
w(text) and set the
newlinekeyword argument to an empty string, which is mandatory when working with CSV files in Python 3.
newline='' is not specified, newlines embedded inside quoted fields are not
For example, on platforms that use
\r\n line endings on write, an extra
will be added unless
newline='' is specified.
If you are writing to an
io.BytesIO object, use the
instead as the csv writer only handles strings.