CSV行追加:DictWriter始终从第一列写入

时间:2017-09-08 14:22:13

标签: python csv

输入文件:

$ 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并附加总和。):

$ 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,那么列的对齐方式非常直观:

enter image description here

2 个答案:

答案 0 :(得分:4)

您应该在with open('test.csv', 'a') as w: writer = csv.DictWriter(w, fieldnames=['company', 'spread']+all_keys) writer.writerow(default_values) 中包含前两个的列名:

#include<stdio.h>

int main(void)
{
    int kertotaulu[15] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
    int kertoja;
    int indeksi;

    for (kertoja = 0; kertoja <= 15; kertoja++) {
        if (kertoja == 0) {
            printf("x");
            printf(" ");
            for (indeksi = 0; indeksi < (sizeof(kertotaulu) / sizeof(kertotaulu[0])); indeksi++) {
                printf("%d", kertotaulu[indeksi]);
                printf(" ");
            }
            printf("\n");   // New Line
            continue;    // Continue, goes to the top of loop again
        }
        for (indeksi = 0; indeksi < (sizeof(kertotaulu) / sizeof(kertotaulu[0])); indeksi++) {
            printf("%d", kertotaulu[indeksi] * kertoja);
            printf(" ");
        }
        printf("\n");
    }
    return 0;
}

如果字典中没有键,则空白值将写入前两列。

答案 1 :(得分:1)

你可以声明你这样写:

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

因此您不必指定所有缺失的键:对于所有缺失的键,restval char将填充您选择的值。 https://docs.python.org/3/library/csv.html#csv.DictWriter