2

I've taken a look online to try and solve this problem and used solutions from other posts to build towards my solution, however from here, I don't get what to do next.

I basically want to grab the final 5 lines of the PastWinners text file and then get the average of those numbers. What I currently have gets the average of the entire document and also prints out the final line in the text file.

with open('PastWinners.txt') as f:
    data = [float(line.rstrip()) for line in f]

    first = f.readline()      # Read the first line.
    f.seek(-2, 2)             # Jump to the second last byte.
    while f.read(1) != b"\n": # Until EOL is found...
        f.seek(-2, 1)         # ...jump back the read byte plus one more.
    last = f.readline()       # Read last line.

biggest = min(data)
smallest = max(data)
print(sum(data)/len(data))
print(last)

Thanks for the help.

Ben Parry
  • 133
  • 1
  • 4
  • 19

3 Answers3

3

You can use slicing to get only the 5 last numbers (I deleted all the irrelevant code):

with open('PastWinners.txt') as f:
    data = [float(line.rstrip()) for line in f]
print(sum(data[-5:])/len(data[-5:]))

the data[-5:] says take only the data from the 5-1 before last item to the last item.

Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31
1

You can read the file in reverse order and use break after 5 reads to get out from the loop. You can also just run 5 iteration of the loop while starting from the end of the file, so you will not have to use break at all.

Here is how to read in reverse in Python.

Community
  • 1
  • 1
Gilsho
  • 63
  • 7
0

This will work when the file is less than 5 lines, too, and will format your average to 2 decimal places.

with open('PastWinners.txt') as f:
    data = [float(line.rstrip()) for line in f]

if len(data) > 5:
    data = data[-5:]

print min(data), max(data), "{:.2f}".format(sum(data)/len(data))
Fhaab
  • 351
  • 1
  • 2
  • 8