Frage

I am using python CSV module to write CSV file. I have used the following code to create the object for writing a CSV file

writer = csv.writer(stringIO, quotechar='"', quoting=csv.QUOTE_ALL)

headers = ['HEADING1','HEADING2']
writer.writerow(headers)
values=['value1','value2']
writer.writerow(values)

But I only want to put double quotes around the values and not the headers.

For example I want the output as follows:

HEADING1,HEADING2
"value1","value2"

But I get the following

"HEADING1","HEADING2"
"value1","value2"

Please can someone suggest how I can get csv file with quotes only around the values and not the headers?

War es hilfreich?

Lösung

Write the headers separately, by creating a new csv.writer() for the rows:

writer = csv.writer(stringIO)
headers = ['HEADING1', 'HEADING2']
writer.writerow(headers)

writer = csv.writer(stringIO, quotechar='"', quoting=csv.QUOTE_ALL)
values=['value1', 'value2']
writer.writerow(values)

csv.writer() objects have no way of switching between dialects. Just create a new object if you have to use a different dialect for some rows.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top