如何在Python中的DictWrite中向标题行项添加“”

时间:2018-01-01 23:12:39

标签: python csv dictionary

我正在尝试编写一个将字典列表传递给csv文件的方法。

我有以下列表:

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}]

以下代码:

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)

我想要:

"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

但我明白了:

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

如何更改我的代码,以便字段名称周围有“?”

1 个答案:

答案 0 :(得分:3)

您可以通过将作者的引用属性设置为quotation marks quotechar 来强制始终" csv.QUOTE_ALL"。但是,正如Daniel Roseman已提到的那样,此属性存在的原因是引用包含,之类的分隔符字符的字段或您选择的任何字符。

以下是设置quotecharquoting的一个小例子:

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

输出names.csv:

"first_name","last_name"

"Baked","Beans"

仅限标题:

如果您对仅使用headers撰写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'}) 的方便函数。

<ImageView
        android:id="@+id/image"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="right|center"/>