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'
答案 0 :(得分:2)
file.readline()
始终返回带有尾随换行符的行,除非它是文件末尾且文件未以换行符结尾,因此如果要将其转换为行,则应strip
行int
或将其与""
进行比较,以结束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