Adding a CSV row: DictWriter always writes from the first column

Input file:

$ 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 expected result (the sum of the columns cat1, cat2and cat3and add the amount.)

$ 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

The code:

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)

Actual output:

$ 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

Question:

csv.DictWriterdoes not add a row with proper column alignment. I understand that I have 5 columns, but I only provide values ​​for three columns. But I thought that this DictWriter, it will add values ​​only to the corresponding column of the column. If I open my CSV Actual Output, it is quite obvious that the columns are not aligned:

enter image description here

+4
source share
2 answers

You must specify 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)

, .

+4

:

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

+1

Source: https://habr.com/ru/post/1685313/


All Articles