How to sum numbers from a text file in Python

Question:

I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).

I have been attempting this problem for hours, and I have what is written below.

I do not know why my code does not seem to be summing up properly.

And the python code:

f=open("C:\Users\Emily\Documents\not_just_numbers.txt", "r")
s=f.readlines()
p=str(s)

for line in s:
    printnum=0
    try:
        printnum+=float(line)
        print("Adding:", printnum)    
    except ValueError:
        print("Invalid Literal for Int() With Base 10:", ValueError)

    for line in s: 
        if p.isdigit():
        total=0            
            for number in s:    
                total+=int(number)
                print("The sum is:", total)
Asked By: Megan

||

Answers:

Every time you enter a new line you reset the total to zero if the number is a digit.

You might want your total to initialize before you enter the loop.


I tried debugging the for loop using the isdigit and isalpha
apparently every new line is not considered a digit or alphanumeric these always evaluate to false

As it turns out you don’t need the for loop you’ve done most of the program with your try except statement

Here’s how I did it on my system.

f = open("/home/david/Desktop/not_just_numbers.txt", 'r')
s = f.readlines()
p = str(s)

total = 0

for line in s:
    #print(int(line))
    printnum = 0
    try: 
        printnum += float(line)
        total += printnum
        #print("Adding: ", printnum)
    except ValueError:
        print("Invalid Literal for Int() With Base 10:", ValueError)

print("The sum is: ", total)
Answered By: David Ruiz

Here is what you can do:

data.txt:

1
2
hello
3
world
4

code:

total = 0

with open('data.txt') as infile:
    with open('results.txt', 'w') as outfile:

        for line in infile:
            try:
                num = int(line)
                total += num
                print(num, file=outfile)
            except ValueError:
                print(
                    "'{}' is not a number".format(line.rstrip())
                )

print(total)


--output:--
'hello' is not a number
'world' is not a number
10


$ cat results.txt
1
2
3
4
Answered By: 7stud

You are checking the wrong condition:

for line in s: 
    if p.isdigit():

p is this:

s=f.readlines()
p=str(s)

Being a strified version of a list, it will start with a '[', and hence p.isdigit() will always be false. You instead want to check line.isdigit(), and you want to only initialise total once instead of each time around the loop:

total = 0
for line in f:
    if line.isdigit():
        total += int(line)

Note that by iterating over f directly, you also don’t need to ever call readlines().

Answered By: lvc

I have a code that relies on me reading a text file, printing off the
numbers where there are numbers, printing off specific error messages
where there are strings instead of numbers, then summing ALL the
numbers up and printing their sum (then saving ONLY the numbers to a
new text file).

So you have to do the following:

  1. Print numbers
  2. Print a message when there isn’t a number
  3. Sum the numbers and print the sum
  4. Save only the numbers to a new file

Here is one approach:

total = 0

with open('input.txt', 'r') as inp, open('output.txt', 'w') as outp:
   for line in inp:
       try:
           num = float(line)
           total += num
           outp.write(line)
       except ValueError:
           print('{} is not a number!'.format(line))

print('Total of all numbers: {}'.format(total))
Answered By: Burhan Khalid

you can also try this:

f=open("C:\Users\Emily\Documents\not_just_numbers.txt", "r")
ww=open("C:\Users\Emily\Documents\not_just_numbers_out.txt", "w")
s=f.readlines()
p=str(s)


for line in s:
    #printnum=0
    try:
        #printnum+=float(line)
        print("Adding:", float(line))
        ww.write(line)
    except ValueError:
        print("Invalid Literal for Int() With Base 10:", ValueError)

total=0 
for line in s: 
    if line.strip().isdigit():
        total += int(line)
print("The sum is:", total)

here str.strip([chars]) means

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

Answered By: Sakib Ahammed
$ echo -e '1/n2/n3/n4/n5' | python -c "import sys; print sum(int(l) for l in sys.stdin)"

This is a very short way to sum all numbers in your file (you will have to add try and except)

import re
print(sum(float(num) for num in re.findall('[0-9]+', open("C:\Users\Emily\Documents\not_just_numbers.txt", 'r').read())))
Answered By: Tostau

Read from file containing numbers separated by new lines:

    total = 0
    with open("file_with_numbers.txt", "r") as f:
        for line in f:
            total += int(line)
    print(total)
Answered By: oystër
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.