Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the sum of values in a column from a text file if matching certain criteria

I'm having some trouble trying add certain values in a column from a text file together. My text file looks like:

e320,2/3/5,6661,c120,A,6661
e420,6/5/3,16916,c849,A,24323
e432,6/5/3,6962,c8429,A,4324
e430,6/5/3,4322,c8491,A,4322
e32042,2/3/5,13220,c1120,A,13220
e4202,6/5/3,4232,c8419,E,4232

I would like to find the sum of the last column's values, provided in the array the third column (final total) is equal to the last column. (amount paid.). The total of all the last column's values should only be found if the fifth column's (status) equals 'E' and finaltotal == amountpaid.

My code so far for this is:

data = open("paintingJobs.txt", "r")
info=data.readlines()
data.close
totalrev=0
for li in info:
    status=li.split(",")[4]
    finaltotal=int(li.split(",")[2])
    amountpaid=int(li.split(",")[5])
    if amountpaid == finaltotal:
        revenue=True
        if status == "A" and revenue == True:
            totalamountpaid = li.split(",")[5]
            total = (sum(totalamountpaid))
            print("The total revenue is")
            print(total)

My desired output would be:

The total revenue is
28435

The total should equal 28435 as 6661+4322+13220+4232=28435 (the sum of the total revenues where status equals 'A' and finaltotal=amountpaid.)

I keep receiving a "TypeError: unsupported operand type(s) for +: 'int' and 'str'". I'm using Python 3.4.3 and a complete newbie to Python. Any help would be much appreciated.

like image 457
Seruza Avatar asked Dec 29 '25 20:12

Seruza


1 Answers

Try this.

total = (sum(totalamountpaid)) 

to

total = (sum(map(int,totalamountpaid.split(',')))) 

Split every number from the string map converting the string to int. Then sum them up.

like image 150
Alvaro Joao Avatar answered Dec 31 '25 12:12

Alvaro Joao