How to read input file of integers separated by space using readlines in Python 3?

I need to read the input file (input.txt), which contains one line of integers (13 34 14 53 56 76), and then calculate the sum of the squares of each number.

This is my code:

# define main program function
def main():
    print("\nThis is the last function: sum_of_squares")
    print("Please include the path if the input file is not in the root directory")
    fname = input("Please enter a filename : ")
    sum_of_squares(fname)

def sum_of_squares(fname):
    infile = open(fname, 'r')
    sum2 = 0
    for items in infile.readlines():
        items = int(items)
        sum2 += items**2
    print("The sum of the squares is:", sum2)
    infile.close()

# execute main program function
main()

If each number is on a separate line, it works fine.

But I can’t figure out how to do this when all the numbers are on the same line, separated by a space . In this case, I get an error:ValueError: invalid literal for int() with base 10: '13 34 14 53 56 76'

+4
source share
4 answers

You can use file.read()to get a string, and then use str.splitto separate by spaces.

string int, sum .

, with, :

def sum_of_squares(fname):

    with open(fname, 'r') as myFile: # This closes the file for you when you are done
        contents = myFile.read()

    sumOfSquares = sum(int(i)**2 for i in contents.split())
    print("The sum of the squares is: ", sumOfSquares)

:

The sum of the squares is: 13242
+5

.

, split ( items.split(' '), , , - . , int, .

, , .:)


, pythonic , .

# The `with` statement is the proper way to open a file.
# It opens the file, and closes it accordingly when you leave it.
with open('foo.txt', 'r') as file:
    # You can directly iterate your lines through the file.
    for line in file:
        # You want a new sum number for each line.
        sum_2 = 0
        # Creating your list of numbers from your string.
        lineNumbers = line.split(' ')
        for number in lineNumbers:
            # Casting EACH number that is still a string to an integer...
            sum_2 += int(number) ** 2
        print 'For this line, the sum of the squares is {}.'.format(sum_2)
+2

, split().

From a document: For example, ' 1 2 3 '.split()returns ['1', '2', '3'].

def sum_of_squares(fname):
    infile = open(fname, 'r')
    sum2 = 0
    for items in infile.readlines():
        sum2 = sum(int(i)**2 for i in items.split())
    print("The sum of the squares is:", sum2)
    infile.close()
+2
source

Just keep it simple, nothing complicated is needed. Here is a commented step-by-step solution:

def sum_of_squares(filename):

    # create a summing variable
    sum_squares = 0

    # open file
    with open(filename) as file:

        # loop over each line in file
        for line in file.readlines():

            # create a list of strings splitted by whitespace
            numbers = line.split()

            # loop over potential numbers
            for number in numbers:

                # check if string is a number
                if number.isdigit():

                    # add square to accumulated sum
                    sum_squares += int(number) ** 2

    # when we reach here, we're done, and exit the function
    return sum_squares

print("The sum of the squares is:", sum_of_squares("numbers.txt"))

What outputs:

The sum of the squares is: 13242
0
source

Source: https://habr.com/ru/post/1690979/


All Articles