Jeff D
Jeff D

Reputation: 1

Calculating average from numbers in .txt file using Python

def main():

    total = 0.0
    length = 0.0
    average = 0.0

    try:
        #Get the name of a file
        filename = input('Enter a file name: ')

        #Open the file
        infile = open(filename, 'r')

        #Read the file's contents
        contents = infile.read()

        #Display the file's contents
        print(contents)

        #Read values from file and compute average
        for line in infile:
            amount = float(line)
            total += amount
            length = length + 1

        average = total / length

        #Close the file
        infile.close()

        #Print the amount of numbers in file and average
        print('There were ', length, ' numbers in the file.' )
        print(format(average, ',.2f'))

    except IOError:
        print('An error occurred trying to read the file.')

    except ValueError:
        print('Non-numeric data found in the file')

    except:
        print('An error has occurred')


main()

This is how the numbers in my .txt file appear:

78
65
99
88
100
96
76

I keep getting "An error has occurred" when I try to run. After I comment that out I get a divisibility error. I tried to just print out the total and length to see if they were actually computing but each is 0.0 so apparently I have some problems in getting them to accumulate correctly.

Upvotes: 0

Views: 27133

Answers (3)

Makoto
Makoto

Reputation: 106390

infile.read() will take the entire file, not individual portions. If you want individual portions, you'll have to split them up (by space) and get rid of the whitespace (that being \n).

Obligatory one-liner:

contents = infile.read().strip().split()

You would then wish to iterate over the contents of contents, as that would be the only thing worth iterating over. infile is already exhausted, and subsequent calls to read() will generate an empty string.

for num in contents:
    amount += float(num)
    # more code here

 average = total / len(contents) # you can use the builtin len() method to get the length of contents instead of counting yourself

Upvotes: 2

mattjegan
mattjegan

Reputation: 2884

I modified you code to see if I could make it work and still look as much like yours as possible. This is what I came up with:

def main():

total = 0.0
length = 0.0
average = 0.0

    try:
        #Get the name of a file
        filename = raw_input('Enter a file name: ')

        #Open the file
        infile = open(filename, 'r')  

        #Read values from file and compute average
        for line in infile:
            print line.rstrip("\n")
            amount = float(line.rstrip("\n"))
            total += amount
            length = length + 1


        average = total / length

        #Close the file
        infile.close()

        #Print the amount of numbers in file and average
        print 'There were', length, 'numbers in the file.' 
        print format(average, ',.2f')

    except IOError:
        print 'An error occurred trying to read the file.' 

    except ValueError:
        print 'Non-numeric data found in the file'

    except:
        print('An error has occurred')

main()

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

infile.read() consumes the file. Consider writing each line as you come across it instead.

Upvotes: 2

Related Questions