Stacey J Stacey J - 5 months ago 6
Python Question

How to create a file and then read integers of it and give an average?

I have to write a program that reads a list of numbers from a file then outputs the average.
If my file contained
3
45
83
21
My program would output: 38
I know how to create the file:

myFile = open('average', 'wt')
myFile.write('3\n')
myFile.write('45\n')
myFile.write('83\n')
myFile.write('21\n')
myFile.close()


This bit works but I don't know how to do the second part.

Answer
with open('average', 'wt') as myFile:
    myFile.write('3\n')
    myFile.write('45\n')
    myFile.write('83\n')
    myFile.write('21\n')

Split number string using str.split, then convert to int. Sum all number, divide it:

with open('average', 'rt') as myFile:
    numbers = map(int, myFile.read().split())
    print(sum(numbers, 0.0) / len(numbers))

If file is huge, above will cause problem (taking too many memory). In such case, use following (process line by line):

with open('average', 'rt') as myFile:
    total, n = 0, 0
    for line in myFile:
        total += int(line)
        n += 1
    print(float(total) / n)