编写一个程序来计算文件中存储的所有数字的平均值

时间:2019-12-25 07:08:20

标签: python

'''
Average Number 
'''

def main ():
    import sys
    try:
        NumberTxt = open("numbers.txt", "r")
    except IOError as e:
        print ("Non-numeric data found in the file   /n press enter" )
    except (ValueError):
        print( "Non-numberic data found in the file /n press enter")
    else:
        TotalNumber = 0
        NumbersOfLines = 0
        line = NumberTxt.readline()

        while line !="":
            NumbersOfLines += 1
            TotalNumber += int( line )
            line = NumberTxt.readline()
        averageNumbers = TotalNumber / NumbersOfLines

        print ( "The average is:", averageNumbers)
        print ( "press enter" )

main()

1 个答案:

答案 0 :(得分:1)

由于信息不完整,最可能的原因是因为您从文件读取的行的末尾仍然有换行符,所以最后一行只是换行符\n,因此{{1} }仍然为真,但是while失败。因此,要修复更改这两行:

int("\n")