首页 > 解决方案 > 如何将数字的总和打印到输出文件中

问题描述

因此,我必须编写一个代码来读取名为“numbers.txt”的输入文件,该文件包含数字 1-10,但是如何让代码在输出文件中记下总和?我的代码已经告诉我总和但是我如何让我的输出文件“outputnumbers.txt”有数字 1-10 加上总和?

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

标签: pythoninputsumnumbersoutput

解决方案


试试下面的。
我只是在for循环完成计算总和后添加了一行outp.write('\n'+str(total))来添加数字的总和

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

数字.txt

1
2
3
4
5
6
7
8
9
10

输出数字.txt

1
2
3
4
5
6
7
8
9
10
55.0

推荐阅读