jboyda5
jboyda5

Reputation: 75

How to find the average of values in a .txt file

I need to find the minimum, maximum, and average of values given in a .txt file. I've been able to find the minimum and maximum values but I'm struggling with finding the average of values. I haven't wrote any coding for determining the average as I have no clue where to start. My current code is:

def summaryStats():
    filename = input("Enter a file name: ")
    file = open(filename)
    data = file.readlines()
    data = data[0:]
    print("The minimum value is " + min(data))
    print("The maximum value is " + max(data))

I need to be able to return the average of these values. As of now the .txt document has the following values:

893
255
504

I'm struggling on being able to find the average of these because every way I try to find the sum my result is 0.

Thanks (sorry I'm just learning to work with files)

Upvotes: 2

Views: 8488

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250891

You should convert the data retrived from file to integers first, because your data list contains strings not numbers. And after the conversion to integers average can be found easily:

Why conversion to int is required?

>>> '2' > '10'  #strings are compared lexicographically
True

Code:

def summaryStats():
    filename = input("Enter a file name: ")
    with open(filename) as f:
        data = [int(line) for line in f]

    print("The minimum value is ", min(data))
    print("The maximum value is ", max(data))
    print("The average value is ", sum(data)/len(data))

Output:

Enter a file name: abc1
The minimum value is  255
The maximum value is  893
The average value is  550.6666666666666

Upvotes: 4

jabaldonedo
jabaldonedo

Reputation: 26572

Don't reinvent the wheel, use numpy it takes a couple of instructions. You can import a txt file into a numpy array and then use the built-in function to perform the operations you want:

>>> import numpy as np
>>> data = np.loadtxt('data.txt')
>>> np.average(data)
 550.666666667
>>> np.max(data)
 893.0
>>> np.min(data)
 255.0

Upvotes: 3

Related Questions