EliranA
EliranA

Reputation: 238

Write CSV in Python 3.x without quotes for first line

I'm trying to find a way to write CSV file from other file. The first line is the header and it must be written without quotes. All other lines must be with quotes.

I tried to work with DictWriter to get the header and write all the rows but still all rows (with the header) are quoted.

Here's an example of what I wrote:

writer = csv.DictWriter(csvOutputFile, fieldnames=FileHeader.getFields(self), delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONNUMERIC)
writer.writeheader()

The output file should look like that:

column1,column2,column3
"1111","2222","3333"

Upvotes: 0

Views: 2755

Answers (2)

Rolf of Saxony
Rolf of Saxony

Reputation: 22443

I suppose you could change the definition of writer from quoting=csv.QUOTE_NONE to quoting=csv.QUOTE_ALL after writing the header.

import csv

with open('eggs2.csv','w') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_NONE)
    spamwriter.writerow(['column1','column2','column3','column...'])
    spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_ALL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
    spamwriter.writerow([1111, 2222, 33333])

Result:

column1,column2,column3,column...
"Spam","Spam","Spam","Spam","Spam","Baked Beans"
"Spam","Lovely Spam","Wonderful Spam"
"1111","2222","33333"

Upvotes: 3

Serge Ballesta
Serge Ballesta

Reputation: 148880

A simple way would be to use 2 different csv writers on the same file object:

writer = csv.DictWriter(csvOutputFile, fieldnames=FileHeader.getFields(self),
    delimiter=',', quotechar='\"', quoting=csv.QUOTE_NONE)
writer.writeheader()
writer = csv.DictWriter(csvOutputFile, fieldnames=FileHeader.getFields(self),
    delimiter=',', quotechar='\"', quoting=csv.QUOTE_ALL)
# actually write the data to writer

Upvotes: 2

Related Questions