【问题标题】:How do I print the sum of the numbers into the output file如何将数字的总和打印到输出文件中
【发布时间】:2019-04-11 02:58:09
【问题描述】:

所以我必须编写一个代码来读取名为“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))

【问题讨论】:

  • 你可能想去掉任何空白处的行 .. line.strip()
  • 另外,如果您希望您的 o/p 仅具有 sum,您可能希望将这些行作为单独的代码块。您当前的代码只是将输入写入输出

标签: python input sum numbers output


【解决方案1】:

尝试以下方法。
我刚刚添加了一行outp.write('\n'+str(total)),在for循环完成计算总和后添加数字总和

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

outputnumbers.txt

1
2
3
4
5
6
7
8
9
10
55.0

【讨论】:

    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 2013-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    相关资源
    最近更新 更多