Megan Megan - 1 month ago 10
Python Question

How to sum numbers from a text file in Python

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)

Answer

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))
Comments