简体   繁体   中英

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"

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

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"

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