Python csv writer : "Unknown Dialect" Error

csv, python, writer

Solution

You need to specify the format of your string:

with open(csvfile, 'wb') as f:
    writer = csv.writer(f, delimiter=',', quotechar="'", quoting=csv.QUOTE_ALL)

You might also want to re-visit your writing loop; the way you have it written you will get one column in your file, and each row will be one character from the results string.

To really exploit the module, try this:

import csv

lines = ["'A','bunch+of','multiline','CSV,LIKE,STRING'"]

reader = csv.reader(lines, quotechar="'")

with open('out.csv', 'wb') as f:
   writer = csv.writer(f)
   writer.writerows(list(reader))

`out.csv` will have:

A,bunch+of,multiline,"CSV,LIKE,STRING"

If you want to quote all the column values, then add `quoting=csv.QUOTE_ALL` to the writer object; then you file will have:

"A","bunch+of","multiline","CSV,LIKE,STRING"

To change the quotes to `'`, add `quotechar="'"` to the writer object.

Problem

I have a very large string in the CSV format that will be written to a CSV file. I try to write it to CSV using the simplest if the python script ``` results=""" "2013-12-03 23:59:52","/core/log","79.223.39.000","logging-4.0",iPad,Unknown,"1.0.1.59-266060",NA,NA,NA,NA,3,"1385593191.865",true,ERROR,"app_error","iPad/Unknown/webkit/537.51.1",NA,"Does+not",false "2013-12-03 23:58:41","/core/log","217.7.59.000","logging-4.0",Win32,Unknown,"1.0.1.59-266060",NA,NA,NA,NA,4,"1385593120.68",true,ERROR,"app_error","Win32/Unknown/msie/9.0",NA,"Does+not,false "2013-12-03 23:58:19","/core/client_log","79.240.195.000","logging-4.0",Win32,"5.1","1.0.1.59-266060",NA,NA,NA,NA,6,"1385593099.001",true,ERROR,"app_error","Win32/5.1/mozilla/25.0",NA,"Could+not:+{"url":"/all.json?status=ongoing,scheduled,conflict","code":0,"data":"","success":false,"error":true,"cached":false,"jqXhr":{"readyState":0,"responseText":"","status":0,"statusText":"error"}}",false""" resultArray = results.split('\n') with open(csvfile, 'wb') as f: writer = csv.writer(f) for row in resultArray: writer.writerows(row) ``` The code returns "Unknown Dialect" Error Is the error because of the script or is it due to the string that is being written? EDIT If the problem is bad input how do I sanitize it so that it can be used by the csv.writer() method?

Original source