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'
Solution 1:
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='':
withopen("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\nlinendings on write an extra\rwill be added. It should always be safe to specifynewline='', since thecsvmodule 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.
Post a Comment for "Write A Csv File In Python : Error With Function Writerows"