Jared Venson
Jared Venson

Reputation: 57

a PYTHON program that takes its input from a file of numbers and calculates the average

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

Answers (2)

U13-Forward
U13-Forward

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

blhsing
blhsing

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

Related Questions