简体   繁体   中英

How do I add “” to header row items in DictWrite at Python

I'm trying to write a method that passes a list of dictionaries to a csv file.

I have the following list:

List = [{'a': 10, 'e': 14, 'b': 11, 'd': 13, 'c': 12}, {'a': 20, 'e': 24, 'b': 
21, 'd': 23, 'c': 22}, {'a': 30, 'e': 34, 'b': 31, 'd': 33, 'c': 32}, {'a': 
40, 'e': 44, 'b': 41, 'd': 43, 'c': 42}]

And the following code:

def ListDic_to_CSV(filename, table, fieldnames, separator, quote):

    with open(filename, "w", newline="") as csvfile:
            csvwrite=csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter =separator, quotechar = quote)
            csvwrite.writeheader()
            for row in table:
                csvwrite.writerow(row)

I'm trying to get:

"a","b","c","d","e"
10,11,12,13,14
20,21,22,23,24
30,31,32,33,34
40,41,42,43,44

But i get:

a,b,c,d,e
10,11,12,13,14
20,21,22,23,24
30,31,32,33,34
40,41,42,43,44

How do i change my code so that the fieldnames have "" around them?

You can force to have always quotation marks " by setting the quoting attribute of your writer to csv.QUOTE_ALL and your quotechar to " . However as Daniel Roseman already mentioned, the reason this attribute exists is to quote fields that contain separator characters like , or or whichever you have selected.

Here is a little example that sets quotechar and quoting :

import csv

with open('names.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_ALL, quotechar='"')
    writer.writeheader()
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

Output names.csv:

"first_name","last_name"

"Baked","Beans"

Header Only:

If you are interested in just having the headers aka fieldnames to be written with quotes you can instead of using writer.writeheader() just do writer.writerow() and compose your own header. Basically, writeheader is nothing more than a convenient function that calls writerow with a dict.

import csv

with open('names3.csv', 'w') as csvfile:
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, quoting=csv.QUOTE_NONE, quotechar=None)
    quotedFieldnames = [(name,'\"{0}\"'.format(name) ) for name in fieldnames]
    customHeader = dict(quotedFieldnames)
    writer.writerow(customHeader)
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})

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