I'm learning how to use files in python, and I'm having a hard time understanding how to code them. My prompt is to assume a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that calculates the average of all the numbers stored in the file. I've created a notepad file called numbers.txt, and I put the numbers 5, 7, 8, 9, 20 all on separate lines, in that file and saved it as such. Here is my code down bellow.
def main():
file_numbers = open('numbers.txt', 'r')
num1 = int(file_numbers.readline(1))
num2 = int(file_numbers.readline(2))
num3 = int(file_numbers.readline(3))
num4 = int(file_numbers.readline(4))
num5 = int(file_numbers.readline(5))
file_numbers.close()
total = (num3 + num2 + num3 + num4 + num5)
average = total / 5
print(f'The numbers are: {num1}, {num2}, {num3}, {num4}, {num5}')
print (f'Their average is: {average}' )
main()
My output is
The numbers are: 5, 5, 66, 77, 220
Their average is: 86.8
Where is the computer getting these numbers? How can I change my code in order for it to output the correct numbers and the correct average?