-1

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')
4

1 回答 1

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))

供将来参考,因为这是相当简单的代码,您可以分别谷歌搜索每个部分,然后将它们拼凑在一起。

于 2013-04-29T01:28:36.530 回答