如何从python中的文本文件中读取数字?
我是 python 的新手,我需要读取文件中的数字,然后将其添加到一个总和中,然后打印所有这些数字。格式不是问题,但这些数字不会每行显示,并且其中一些数字之间有空行和空格。我如何命令解释器将它通常识别为字符串的行视为整数?这是文件,这是我的代码。
line = eval(infile.read())
while infile != "":
sum = sum + int(line)
count = count + 1
line = eval(infile.read())
print("the sum of these numbers is", sum)
数字>>:
111
10 20 30 40 50 60 70
99 98 97
1
2
33
44 55
66 77 88 99 101
123
456
回答
本质上,您需要执行以下操作:
- 您需要一个变量来存储文件中数字的总和
- 您应该使用
open以在with语句中打开文件,我假设您的文件名为file.txt. - 您需要逐行迭代文件对象。
- 您需要转换字符串列表中的当前行,其中每个元素字符串代表一个数字。假设文件中的所有元素都是整数,并用空格分隔。
- 您需要将该字符串列表转换为整数列表
- 您需要将步骤 5. 列表中的元素相加,并将结果添加到总数中
total = 0 # variable to store total sum
with open('file.txt') as file_object: # open file in a with statement
for line in file_object: # iterate line by line
numbers = [int(e) for e in line.split()] # split line and convert string elements into int
total += sum(numbers) # store sum of current line
print(f"the sum of these numbers is {total}")