pythonsumtxtraw

Sum last N values of a specific column from a txt files


I have a txt file. There are two columns, date and value:

08/12/2023 81.3 
09/12/2023 80.8 
10/12/2023 80.9 
11/12/2023 81.0 
12/12/2023 81.1 
13/12/2023 81.5 
14/12/2023 80.1 
15/12/2023 81.0 
16/12/2023 80.9 
17/12/2023 80.6

I would like to sum, after updated it, the last 7 values of the second column.

mysum = 0
N = 7
with open('/storage/emulated/0/Python/lista.txt','r') as f:
    for line in (f.readlines() [-N:]):
        print(line, end ='')

with open('/storage/emulated/0/Python/lista.txt','r') as f:        
    for line in f:
        mysum += float(line.split()[1])
media = mysum/7        
print(media)

I have the code above, but it does not work.

Any help?


Solution

  • My code reads all lines from the file, extracts the last 7 lines, and then calculates the sum and average of the second column values from those lines.

    This is update code:

    file_path = '/storage/emulated/0/Python/lista.txt'
    
    with open(file_path, 'r') as f:
        lines = f.readlines()
    
    N = 7
    last_lines = lines[-N:]
    
    mysum = sum(float(line.split()[1]) for line in last_lines)
    
    average = mysum / N
    
    print("Sum of the last 7 values:", mysum)
    print("Average of the last 7 values:", average)