计算两个不同CSV文件python之间的值差异

时间:2016-01-27 03:30:30

标签: python csv

我有两个不同的csv文件:

  

outputnovember.csv

symbol,name,amount
A,john,2
D,mary,6
E,bob,9
m,liz,-8
p,peter,-2

总共2,正总数17,负总数-10

  

outputdecember.csv

symbol,name,amount
A,john,2
D,mary,26
m,liz,-1
p,peter,-2

总共2,正总数26,负总数-3

如何计算两个文件的计算值之间的差异,以便将以下内容附加到12月:总共0,Posiitve总计9,负总计-17

到目前为止,这是我的代码:

import csv

f=open('outputnovember.csv')
csv_f= csv.reader(f)

with open('input.csv', 'r') as f_input, open('outdecember.csv', 'w') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    header = next(csv_input)
    csv_output.writerow(header)

    sum_positive = sum_negative = sum_a = 0

    for cols in csv_input:
        csv_output.writerow(cols)
        value = int(cols[2])

        if cols[0] == 'A':
            sum_a += value
        if value >= 0:
            sum_positive += value
        else:
            sum_negative += value


        csv_output.writerow(["A total {}".format(sum_a)],
        csv_output.writerow(["Positive total {}".format(sum_positive)]) 
        csv_output.writerow(["Negative total {}".format(sum_negative)])

...这里是我无法从outputnovember.csv中检索值并找到与outputdecember.csv的区别

谢谢大家 乙

0 个答案:

没有答案