简体   繁体   English

如何将数字从python中的文件转换为整数

[英]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.

相关问题 如何从 txt 文件中提取字符串(数字)并使用 python 中的正则表达式转换为整数 - How to extract string (numbers) from txt file and convert to integers using regular expressions in python 将纯数字从文件转换为整数列表 - Convert plain numbers from file to list of integers 如何在 Python 中将数字列表转换为整数? - How to Convert List of Numbers to Integers in Python? 如何将 Python 文件中的字符串数字转换为整数? - How to change the string numbers into integers from a file in Python? 如何转换从文本文件中读取的整数并存储为具有16位整数的二进制文件? - How to convert integer numbers read from a text file and store as a binary file having 16bit integers? 如何将带有字符串的文件中的数字转换为python列表中的整数 - How to convert numbers from file with strings to integer in a list in python 如果它们在 python 中有标题,我如何从文件中获取数字并将它们作为整数读取? - How do I take numbers from a file and read them as integers if they have headings in python? 从包含素数的文件到 Python 上的整数列表 - From a file containing prime numbers to a list of integers on Python 使用 Python 将带有数字的字符串转换为整数列表 - Convert a string with numbers into a list of integers using Python Python 将字符串数字序列转换为整数列表 - Python Convert sequence of string numbers to list of integers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM