一个PYTHON程序,它从数字文件中获取输入并计算平均值

时间:2018-07-18 02:19:52

标签: python python-3.x programming-languages

def main():
    numbersFile=open("numbers.txt" , 'r')

    line=numbersFile.readline()
    total=0
    numberoflines=0

    while line != " ":
        numberoflines+=1
        total+=int(line)
        line=numbersFile.readline()
    average=total/numberoflines
    print("The average is: " , average)

main() 

该程序显示错误消息-

ValueError:以10为底的int()无效文字:'\ n'

2 个答案:

答案 0 :(得分:2)

file.readline()始终返回带有尾随换行符的行,除非它是文件末尾且文件未以换行符结尾,因此如果要将其转换为行,则应stripint或将其与""进行比较,以结束while循环:

def main():
    numbersFile = open("numbers.txt", 'r')

    line = numbersFile.readline().strip()
    total = 0
    numberoflines = 0

    while line != "":
        numberoflines += 1
        total += int(line)
        line = numbersFile.readline().strip()
    average = total / numberoflines
    print("The average is: ", average)


main()

答案 1 :(得分:1)

def main():
    numbersFile=open("numbers.txt" , 'r')

    line=numbersFile.readline().rstrip()
    total=0
    numberoflines=0

    while line!='':
        numberoflines+=1
        total+=int(line.rstrip('\\n'))
        line=numbersFile.readline().rstrip()
    average=total/numberoflines
    print("The average is: " , average)

main() 

输出:

The average is:  2.5