简体   繁体   中英

How do I read numbers from a text file in python?

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:

  1. You need a variable in which you will store the total sum of the numbers in your file
  2. You should use open in order to open the file in a with statement, I am assuming your file is called file.txt .
  3. You need to iterate a file object line by line.
  4. You need to convert the current line in a list of strings in which each element string represents a number. It is assumed all the elements in the file are integers and that they are separated by spaces.
  5. You need to convert that list of strings into a list of integers
  6. You need to sum the elements in the list of step 5. and add the result to total
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM