How to add "" to title bar elements in DictWrite in Python

I am trying to write a method that transfers 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 am 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 field names have around them?

+4
source share
1 answer

You can force to always quotation marks "set the quoting parameter of your writer to csv.QUOTE_ALLand your quotechar to ". However, as already mentioned, the Daniel Rosemanreason this attribute exists is to specify fields containing separator characters, such as ,or or depending on what you select.

, quotechar 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'})

.csv:

"first_name","last_name"

"Baked","Beans"

:

, headers aka fieldnames quotes, writer.writeheader() writer.writerow() . , writeheader , writerow 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'})
+3

Source: https://habr.com/ru/post/1691601/


All Articles