[Solved] Count certain values of file in python


Here, you can try this one:

summation = 0

with open("test.txt", "r") as infile:
    for line in infile:
        newLine = line.split(", ")
        summation = summation + int(newLine[3])

print(summation)

Output:

3784

The contents of test.txt file are structured like this:

[52639 - 2017-12-08 11:56:58,680] INFO main.master 251 Finished pre-smap protein tag ('4h02', [], 35000, 665, '67')
[52639 - 2017-12-08 11:57:37,686] INFO main.master 251 Finished pre-smap protein tag ('4nqk', [], 35000, 223, '18')
[52639 - 2017-12-08 11:58:46,984] INFO main.master 251 Finished pre-smap protein tag ('3j60', [], 3500, 1052, '65')
[52639 - 2017-12-08 12:01:10,073] INFO main.master 251 Finished pre-smap protein tag ('4ddg', [], 35000, 541, '38')
[52639 - 2017-12-08 12:03:37,570] INFO main.master 251 Finished pre-smap protein tag ('4ksl', [], 35000, 1303, '68')

If you wish to print all the number that make the sum, you can use a list to store each number:

summation = 0
coefficients = []

with open("test.txt", "r") as infile:
    for line in infile:
        newLine = line.split(", ")
        coefficients.append(newLine[3])
        summation = summation + int(newLine[3])

print("+".join(coefficients), end="=")
print(summation)

Output:

665+223+1052+541+1303=3784

7

solved Count certain values of file in python