[SOLVED] How do I find the highest value number of a text file?


This Content is from Stack Overflow. Question asked by Jonas AAT

I have a text file with many lines of numbers and wish to find the highest number. I have already found the average of all the numbers.

Here is my code so far:

“` `file = open(‘max_vind_sola_enkelttall.txt’, ‘r’) lines =
file.read sum = 0

for lines in file:
sum += float(lines) amount = 362 average = sum/amount print(“average is: “, average)

file.close()` “`


Dealing with min and max are very similar to dealing with accumulating the sum/total.

with open('max_vind_sola_enkelttall.txt') as file:

    total = 0
    count = 0
    mn = float('inf')
    mx = float('-inf')

    for line in file:
        count += 1
        v = float(line)
        total += v
        if v < mn:
            mn = v
        if v > mx:
            mx = v

average = total / count
print("average is: ", average)
print("max is: ", mx)
print("min is: ", mn)

Note that I used a with clause to make sure that the file gets closed properly no matter what else happens. These days, we should seldom be calling close() on a stream explicitly, especially when reading and writing local files like this.

This Question was asked in StackOverflow by Jonas AAT and Answered by CryptoFool It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?