Search code examples
pythontextmaxaverageminimum

Finding average in .txt file python


i need to print out average height from a .txt file. How do I write it in an easy way? The .txt file has these numbers:

12
14
59
48
45
12
47
65
152

this is what i've got so far:

import math

text = open(r'stuff.txt').read()
data = []
with open(r'stuff.txt') as f:
    for line in f:
        fields = line.split()
        rowdata = map(float, fields)
        data.extend(rowdata)

biggest = min(data)
smallest = max(data)
print(biggest - smallest)

Solution

  • To compute the average of some numbers, you should sum them up and then divide by the number of numbers:

    data = []
    with open(r'stuff.txt') as f:
        for line in f:
            fields = line.split()
            rowdata = map(float, fields)
            data.extend(rowdata)
    
    print(sum(data)/len(data))