Reputation: 57
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()
this program displays an error message-
ValueError: invalid literal for int() with base 10: '\n'
Upvotes: 1
Views: 294
Reputation: 71610
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()
Output:
The average is: 2.5
Upvotes: 1
Reputation: 107040
file.readline()
always returns the line with a trailing newline unless it is the end of file and the file does not end with a newline, so you should strip
the line if you want to convert it to int
or to compare it with ""
as a condition to end the while
loop:
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()
Upvotes: 2