[英]How to convert numbers to integers from a file in python
Assume that a file containing a series of integers is named numbers.txt.假设包含一系列整数的文件名为 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.现在请学习做你自己的功课。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.