简体   繁体   中英

Write a csv file in Python : error with function writerows

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM