python - 如何将数字的总和打印到输出文件中
问题描述
因此,我必须编写一个代码来读取名为“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))
解决方案
试试下面的。
我只是在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
推荐阅读
- python - 试图做一个猜猜我在 Python 上使用 GUI 制作的数字游戏。但是程序在运行时没有响应
- python - Plotly Choropleth 地图在 Jupyter 中成功加载,但不是 Dash 浏览器
- javascript - 为什么要把赋值语句放在括号中?
- selenium - 如何在量角器中处理 shadow DOM 中的元素?deepcss 不工作
- ruby-on-rails - Ruby on Rails Cloudinary 错误:“Cloudinary”缺少服务适配器
- c# - 操纵杆坐标
- c# - SQLite 日历周开始
- css - 为什么我不能在 Ruby on Rails 中不使用 !important 来更改 link_to 文本颜色?
- spring - 无法获取查询元数据 org.postgresql.util.PSQLException 的连接:连接尝试失败
- elixir - Elixir Mix 版本 - 如何将额外文件复制到 Phoenix 应用程序的压缩包中?