Search code examples
pythondel

how do you delete the line with the biggest number from a text file python?


with open('winnernum.txt', 'r') as b:
  data = b.readlines()
  gone=(max(data))
  print(gone)
with open("winnernum.txt","r") as h:
  del gone

I've tried this and other variations of this code in python but it still won't delete. I need to print the top 5 largest numbers from a text file.

I've attempted using this before:

with open('winners.txt', 'r') as b:
  data = b.readlines()
  gone=(max(data))
  print(gone)
import heapq
print(heapq.nlargest(5, winner))

but that doesn't always pick the top 5 numbers and tends to select them at random. Please help!


Solution

  • Here is a simple solution:

    from heapq import nlargest
    
    with open("winnernum.txt", "r") as f:
        numbers = [float(line.rstrip()) for line in f.readlines()]
        largest = nlargest(5, numbers)
    
    print(largest)