因此,我必须创建一个代码,该代码读取名为“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))
请尝试以下方法。
我刚刚添加了一行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))
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