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