从文件读取和平均总数

时间:2013-04-29 01:09:53

标签: python list exception-handling average

Python 3.x. 我试图从一个名为numbers.txt的文件中读取。其中有几行数字。我需要打印总数和平均值。除此之外,我还需要对IOerror和ValueError使用异常处理。

提前谢谢你。我知道有这样的问题,但建议错误了。

def main():
    total = 0.0
    length = 0.0
    average = 0.0
    try:
        filename = raw_input('Enter a file name: ')
        infile = open(filename, 'r')
        for line in infile:
            print (line.rstrip("\n"))
            amount = float(line.rstrip("\n"))
            total += amount
            length = length + 1
        average = total / length
        infile.close()
        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')

1 个答案:

答案 0 :(得分:1)

with open('numbers.txt', 'r') as my_file:
    try:
        data = [float(n) for n in my_file.read().split()]
    except (IOError, ValueError):
        data = []
total = sum(data)
average = total / len(data)
print('Numbers: {nums}\nTotal: {total}\nAverage: {average}'.format(nums = data, total = total, average = average))

为了将来参考,因为这是相当简单的代码,您可以单独Google各个部分,然后将它们拼凑在一起。