CSV行附加:DictWriter始终从第一列写入 [英] CSV row appending: DictWriter always writes from first column

查看:256
本文介绍了CSV行附加:DictWriter始终从第一列写入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入文件:

$ cat test.csv 
company,spread,cat1,cat2,cat3
A,XYZ,32,67,0
B,XYZ,43,0,432
C,XYZ,32,76,32
D,XYZ,454,87,43
E,XYZ,0,0,65
F,XYZ,0,0,7

预期的CSV输出(列cat1cat2cat3的总和并附加总和.):

Expected CSV output (Sum columns cat1, cat2 and cat3 and append the sum.):

$ cat test.csv 
company,spread,cat1,cat2,cat3
A,XYZ,32,67,0
B,XYZ,43,0,432
C,XYZ,32,76,32
D,XYZ,454,87,43
E,XYZ,0,0,65
F,XYZ,0,0,7
,,561,230,579

代码:

import csv

all_keys = ['cat1', 'cat2', 'cat3']
default_values = {i: 0 for i in all_keys}

def read_csv():
    with open('test.csv', 'r') as f:
        reader = csv.DictReader(f)
        yield from reader

for row in read_csv():
    for i in all_keys:
        default_values[i] += int(row[i])

with open('test.csv', 'a') as w:
    writer = csv.DictWriter(w, fieldnames=all_keys)
    writer.writerow(default_values)

实际输出:

$ cat test.csv 
company,spread,cat1,cat2,cat3
A,XYZ,32,67,0
B,XYZ,43,0,432
C,XYZ,32,76,32
D,XYZ,454,87,43
E,XYZ,0,0,65
F,XYZ,0,0,7
561,230,579

问题:

csv.DictWriter没有追加具有正确列对齐的行.我知道我有5列,但是我只提供3列的值.但是我认为这是DictWriter,它将仅将值附加到匹配的列标题中.如果我打开Actual Output CSV,则很明显列未对齐:

The csv.DictWriter is not appending row with correct column alignment. I understand that I have 5 columns but I am providing values for only 3 columns. But I thought as this is DictWriter, it will append values to only a matching column header. If I open my Actual Output CSV, it is quite visual that columns are not aligned:

推荐答案

您应在fieldnames中包括前两个列的名称:

You should include the column names for the first two in fieldnames:

with open('test.csv', 'a') as w:
    writer = csv.DictWriter(w, fieldnames=['company', 'spread']+all_keys)
    writer.writerow(default_values)

如果键在词典中不可用,则空白值将写入前两列.

Blank values will be written to the first two columns if the keys are not available in the dictionary.

这篇关于CSV行附加:DictWriter始终从第一列写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆