如何将数字之和打印到输出fi中

2024-07-04 05:24:02 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我必须编写一个代码来读取我的输入文件名为“数字.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))

Tags: 文件代码txtformatasline数字open
1条回答
网友
1楼 · 发布于 2024-07-04 05:24:02

尝试以下操作。
我刚刚添加了一行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

相关问题 更多 >

    热门问题