Moses
Moses

Reputation: 45

How do I print the sum of the numbers into the output file

So I have to make a code that reads my input file named as "numbers.txt" that consists the numbers 1-10 but how would I make the code write down the sum in the output file?. My code already tells me the total sum but how would I make my output file "outputnumbers.txt" have the numbers 1-10 plus the sum?

total = 0

with open('numbers.txt', 'r') as inp, open('outputnumbers.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))

Upvotes: 0

Views: 395

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Try the following.
I just added a line outp.write('\n'+str(total)) to add the sum of numbers after the for loop finishes calculating the sum

total = 0

with open('numbers.txt', 'r') as inp, open('outputnumbers.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))
   outp.write('\n'+str(total))

print('Total of all numbers: {}'.format(total))

numbers.txt

1
2
3
4
5
6
7
8
9
10

outputnumbers.txt

1
2
3
4
5
6
7
8
9
10
55.0

Upvotes: 1

Related Questions