Python:为csv.DictWriter设置一个quotechar?

时间:2018-03-28 05:49:30

标签: python python-3.x

有没有办法为csv.DictWriter()字段名设置quotechar,类似于如何使用csv.reader()设置quotechar?我特别感兴趣的是使用下面quote变量定义的指定quotechar来包围非数字字段名称条目。

我想要

    fieldnames = ['a', 'b', 'c', 'd', 'e']
    separator = ','
    quote = '"'
    table = [{'a': 10, 'c': 12, 'b': 11, 'e': 14, 'd': 13}]

    with open('output1.csv', 'w') as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames = fieldnames, delimiter = separator)
        writer.writeheader()
        for row in table:
            writer.writerow(row)

输出

"a","b","c","d","e"
10,11,12,13,14

quote = '"'而不是

a,b,c,d,e
10,11,12,13,14

2 个答案:

答案 0 :(得分:2)

import csv

fieldnames = ['a', 'b', 'c', 'd', 'e']
separator = ','
quote = '"'
table = [{'a': 10, 'c': 12, 'b': 11, 'e': 14, 'd': 13}]

with open('output1.csv', 'w') as csvfile:
    writer = csv.DictWriter(
        csvfile,
        fieldnames=fieldnames,
        delimiter=separator,
        quotechar=quote,
        quoting=csv.QUOTE_NONNUMERIC,
    )
    writer.writeheader()
    for row in table:
        writer.writerow(row)

我认为您正在寻找csv.QUOTE_NONNUMERIC

答案 1 :(得分:0)

你可以,但是你需要两个不同的编写器,因为显然你想引用标题而不是数据行:

with open('output1.csv', 'w') as csvfile:
    quoted = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=separator, quoting=csv.QUOTE_ALL)
    quoted.writeheader()

    writer = csv.DictWriter(csvfile, fieldnames=fieldnames, delimiter=separator)
    for row in table:
        writer.writerow(row)