0

I know there are a couple of post about this question on S.O. but they have not helped me solve my problem. I am trying to use an accumulator to sum up the values in a text file. When there is a number on each line my code just prints each line that is in the file. When there is a blank space between I get an error message. I think it is a simple oversight but I am new to Python so I am not sure what I am doing wrong.

My code:

def main():
    #Open a file named numbers.txt
    numbers_file = open('numbers.txt','r')
    #read the numbers on the file
    number = numbers_file.readline()

    while number != '':
        #convert to integer
        int_number = int(number)
        #create accumulator
        total = 0
        #Accumulates a total number
        total += int_number
        #read the numbers on the file
        number = numbers_file.readline()
        #Print the data that was inside the file
        print(total)
    #Close the the numbers file
    numbers_file.close()

#Call the main function
main()

Inputs in the text file:

100

200

300

400

500

Gives me error message:
ValueError: invalid literal for int() with base 10: '\n'

Inputs in the text file:

100
200
300
400
500

Prints:
100
200
300
400
500
Part_Time_Nerd
  • 994
  • 7
  • 26
  • 56

3 Answers3

1

You need to exclude empty lines because you can't convert them to an int(). One pythonic (EAFP) way to do this is to catch the exception and ignore (though this will silently ignore any non-number line):

with open('numbers.txt','r') as numbers_file:
    total = 0
    for line in numbers_file:
        try:
            total += int(line)
        except ValueError:
            pass
print(total)

Or you can explicitly test that you don't have an empty string after you .strip() all the whitespace (this would still error for a non-numeric line, e.g. 'hello'):

with open('numbers.txt','r') as numbers_file:
    total = 0
    for line in numbers_file:
        if line.strip():
            total += int(line)
print(total)

This second one can be written as a generator expression:

with open('numbers.txt','r') as numbers_file:
    total = sum(int(line) for line in numbers_file if line.strip())
print(total)
AChampion
  • 29,683
  • 4
  • 59
  • 75
0

You are assigning the value 0 to your accumulator each time you go through the loop, before you add the new value. This means you're adding the new value to 0 each time, which means you're just printing the new value.
If you move the line total = 0 to occur before the loop, then it should work as you were hoping.

If you want, you can clean this up a little:

numbers_file = open('numbers.txt','r')    
total = 0
for number in numbers_file:
    if number:  
        int_number = int(number)
        total += int_number
        print(total)
numbers_file.close()

would be a first pass. The check if number returns True if number contains a "truthy" value, which in this case would happen if you hit an empty line.

Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
0

Hi you are missing to remove the 'new line symbol' which is \n. To ensure you get only literals that can be converted to numbers you have to strip other characters. With e.g.

a = '100\ntest'
print(a.isnumeric())
a = '103478'
print(a.isnumeric())

You can test if there is a character that prevents conversion to a number. The regular expression package to manipulate string easily.

See this stack overflow threat.

import re
a = jkfads1000ki'
re.sub('\D','',a)
'1000'

See the Python docs on re.

Henning
  • 95
  • 1
  • 1
  • 7