Home > Enterprise >  Sum of rows from CSV
Sum of rows from CSV

Time:09-29

I have the following code:

with open("expenses.csv") as read_exp:
    reader = csv.reader(read_exp, delimiter=',')
    header = next(reader)
    if header != None:
        for row in reader:
            month_str = row[0]
            month_dt= datetime.strptime(month_str, '%d/%m/%Y').month       
            if month_dt == month1:
                sum1 = sum((map(int,row[2:7])))
                print(sum1)

This gives me the sum of each individual row that is from the month I am looking for.

Output:

Enter selected month number: 7
Selected Month is: July
15
26
7
23
21
19
30

Is there a way to combine the individual sums into one total sum?

My csv is as below:

Date,Budget,Groceries,Transport,Food,Bills,Others
12/7/2021,30,1,0,4,2,8
13/7/2021,30,9,3,5,7,2
14/7/2021,30,3,3,0,0,1
15/7/2021,30,1,0,10,7,5
16/7/2021,30,9,9,0,2,1
17/7/2021,30,0,6,4,1,8
18/7/2021,30,0,9,9,8,4
16/8/2021,30,7,10,7,10,1
17/8/2021,30,5,6,10,9,1
18/8/2021,30,6,1,9,10,5
19/8/2021,30,0,8,8,3,5
20/8/2021,30,4,0,6,9,4
21/8/2021,30,6,2,1,1,5
22/8/2021,30,3,3,1,1,10
13/9/2021,30,8,2,9,4,6
14/9/2021,30,10,7,10,5,7
15/9/2021,30,5,5,6,9,6
16/9/2021,30,5,7,4,6,2
17/9/2021,30,3,7,10,5,7
18/9/2021,30,8,9,6,8,1
19/9/2021,30,5,3,1,9,5

CodePudding user response:

I assume you want to print the full value of the month in your example correct?

If that is the case you could just have a variable total_sum for example where u add the content of sum1(I m assuming sum1 is a value) into it like this:

    reader = csv.reader(read_exp, delimiter=',')
    header = next(reader)
    if header != None:
        for row in reader:
            month_str = row[0]
            month_dt= datetime.strptime(month_str, '%d/%m/%Y').month       
            if month_dt == month1:
                sum1 = sum((map(int,row[2:7])))
                print(sum1)
                total_sum  = sum1
                print(total_sum)
  • Related