从文件和averag读取

2024-04-24 19:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 3.x版 我试图从一个名为数字.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')

Tags: theinline数字filenameamountlengthinfile
1条回答
网友
1楼 · 发布于 2024-04-24 19:45:03
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))

为了将来的参考,因为这是一个相当简单的代码,你可以单独谷歌每个部分,你可以拼凑起来。在

相关问题 更多 >