0

i want to add ints that is stored in a file and add the numbers to find the total.. i took this code from a txt book but im getting the following error :

invalid literal for int() with base 10: '1 2 3 12 4 55'

how can i solve this if i want to read the numbers one by 1 not by using a list

f = open("intgers.txt", 'r')
theSum = 0
for line in f:
    line = line.strip()
    number = int(line)
    theSum += number
print("The sum is", theSum)

3 Answers3

0

You need to split the line.

f = open("intgers.txt", 'r')
theSum = 0
for line in f:
    numbers = line.strip().split(' ')
    for number in numbers:
        n = int(number)
        theSum += n
print("The sum is", theSum)
Ludal
  • 110
  • 1
  • 7
0

Using this code block, you're assuming each of the numbers are separated by new lines in intgers.txt. As the error suggests, the line variable is '1 2 3 12 4 55'. You can't convert that to an integer. You need to parse this into a list of numbers first:

f = open("intgers.txt", 'r')
theSum = 0
for line in f:
    numbers = line.split()
    for num in numbers:
        number = int(num.strip())
        theSum += number
print("The sum is", theSum)

Look into uses of string methods strip() and split() if you're confused.

Zahin Zaman
  • 210
  • 3
  • 9
0

It appears that there are multiple space-separate integers on each line. You need to .split() each line and iterate over the resulting list to add the numbers from that line.

f = open("intgers.txt", 'r')
theSum = 0
for line in f:
    splitline = line.strip().split()
    for item in splitline:
        number = int(item)
        theSum += number
print("The sum is", theSum)

There are a number of improvements that can be made to this, using map to apply the int function across the list and using implicit iteration to get a sum directly from each line. For interest:

f = open("intgers.txt", 'r')
theSum = 0
for line in f:
    theSum += sum(map(int, line.strip().split()))
print("The sum is", theSum)
Joffan
  • 1,485
  • 1
  • 13
  • 18