Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:为csv.DictWriter设置引号?_Python_Python 3.x - Fatal编程技术网

Python:为csv.DictWriter设置引号?

Python:为csv.DictWriter设置引号?,python,python-3.x,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':

有没有一种方法可以为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

可以,但您需要两个不同的写入程序,因为显然您希望引用标题而不是数据行:

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)

我想您正在寻找的是,仅添加quoting=csv.QUOTE“非数字”并不能解决问题,但引用csv.QUOTE“非数字”使我了解了如何定义所使用的引号。添加quotechar=QUOTE,quoting=csv.QUOTE“非数字”作为csv.DictWriter的参数似乎正是我需要的。我将运行两个测试It’今晚和早上,很快接受答复。
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)