[英]How do I read numbers from a text file in 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
。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}")
import re
with open(filename, "r")as f:
l = []
for line in f:
l.extend(re.findall(r"\d+", line.strip()))
print("the sum of these numbers is", sum(map(int, l)))
您可以遍历文件的每一行并将数字添加到我们的total
中。
total = 0
with open("input.txt") as file:
for line in file.readlines():
total += sum(map(int, line.split()))
print(total)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.