Python:读取文件并计算sum和averag

2024-05-16 21:35:24 发布

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

问题是逐行读取文件,计算并显示文件中所有有效数字的总和和平均值。

文本文件是

contains text
79.3
56.15
67
6
text again 
57.86
6
37.863
text again 
456.675

到目前为止我只有这些。

numbers = open('fileofnumbers.txt', 'r')

line = file_contents.readline()

numbers.close()

try:
    sum = line + line
    line = file_contents.readline()
    print "The sum of the numbers is", sum


except ValueError:
    print line

Tags: 文件textreadlinelinecontentsfile平均值sum