计算文件中数字的平均值

时间:2013-12-05 23:04:02

标签: python file average

所以我要做的就是弄清楚如何向用户询问文本文件并输出所有数字的平均值。通过修补我已经弄清楚如何找到我所制作的列表的平均值,但不知道如何做一个用户给我的列表。这就是我现在所拥有的:

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

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

2 个答案:

答案 0 :(得分:2)

假设文件的每一行都有一个数字:

with open(input('Filename: '), 'r') as f:
    numbers = [int(a.strip()) for a in f]
print('Average is {}'.format(sum(numbers)/len(numbers)))

答案 1 :(得分:0)

这样的东西?

import string

fileName = raw_input("What file name: ")
lines = []
try:
    file = open(fileName)
    lines = file.readlines()
    file.close()
except:
    print "Unable to open file"
sum = 0
values = 0
if(len(lines) > 0):
    for line in lines:
        value = 0
        try:
            value = int(string.strip(line))
        except ValueError:
            pass
        if(value != 0):
            sum = sum + value
            values += 1
    print "Average = %f for %d lines, sum = %f"%(sum/values,values,sum)
else:
    print "No lines in the file"

注意:这假定每行一个数字。它不会计算空白行或有文本的行。除此之外,行上的垃圾或坏文件不应导致异常等。

这是测试文件(有空行):

10
20
30
40
50
23
5



asdfadfs

s

输出:

What file name: numbers.txt
Average = 25.000000 for 7 lines, sum = 178.000000