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

Viewed 54

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()
3 Answers

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.

file = open('max_vind_sola_enkelttall.txt', 'r')
lines = file.read

sum = 0
max = 0
for lines in file:
    sum += float(lines)
    if float(lines) > max:
        max = lines
amount = 362
average = sum / amount
print("average is: ", average)
print("max is: ", max)

If your numbers are a list of floats, you can use the max function with your list as the input.

ex.

file = open('max_vind_sola_enkelttall.txt', 'r')
lines = file.readlines()

lines = [float(x) for x in lines]

largest_float = max(lines)
print(largest_float)

https://docs.python.org/3/library/functions.html#max

Related