1

Trying to save a list of lists into a csv file, I used the csv module. Here is my script :

import csv
a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]
with open("output.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(a)

When I run this script, an error message appears :

Traceback (most recent call last):
File "csv-ex.py", line 5, in <module>
writer.writerows(a)
TypeError: a bytes-like object is required, not 'str'

Anyone knows what is missing?

1 Answer 1

5

You opened the file in binary mode, but the csv.writer() object sends strings.

Open the file in text mode by dropping the b. It is also recommended you set newline='':

with open("output.csv", "w", newline='') as f:

See the csv module footnote:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='', since the csv module does its own (universal) newline handling.

In Python 2, it was recommended to open the file in binary mode for the same reasons, but the I/O layer in Python 3 handles this much better with the newline option.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.