简体   繁体   中英

How to convert numbers to integers from a file in python

Assume that a file containing a series of integers is named numbers.txt. Write a program that calculates the average of all the numbers stored in the file.

Above is the program I must write and here is what I have so far for code below is what I wrote for code. Is there a way I can code this so no matter how many numbers are in the file it works.

infile = open('numbers.txt', 'r')
num1 = int(infile.readline())
num2 = int(infile.readline())
num3 = int(infile.readline())
num4 = int(infile.readline())
num5 = int(infile.readline())
num6 = int(infile.readline())
num7 = int(infile.readline())
num8 = int(infile.readline())
num9 = int(infile.readline())
num10 = int(infile.readline())
infile.close()

total = num1+num2+num3+num4+num5+num6+num7+num8+num9+num10

a = total/10

print (a)
loop_count = 0
total = 0
data = open("numbers.txt","r")
for line in data.readlines():
    total = total + int(line)
    loop_count += 1
avg = total/loop_count

Now please learn to do your own homework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM