I'm new to python, and I need to read and then add numbers from a file into one sum and then print all of them. Formatting isn't an issue, but these numbers are not displayed on one line each, and there are blank lines and spaces between some of them. How do I command the interpreter to see the lines that it would normally recognize as strings, as integers? Here's the file, and here's my code.
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)
the numbers >>:
111
10 20 30 40 50 60 70
99 98 97
1
2
33
44 55
66 77 88 99 101
123
456
In essence you need to do the following:
open
in order to open the file in a with
statement, I am assuming your file is called 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)))
You can just iterate over every line of the file and add the numbers to our total
.
total = 0
with open("input.txt") as file:
for line in file.readlines():
total += sum(map(int, line.split()))
print(total)
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.