如何在 Python 中对文本文件中的数字求和
问题描述
我有一个代码依赖于我读取文本文件,打印出有数字的数字,打印出有字符串而不是数字的特定错误消息,然后将所有数字相加并打印它们的总和(然后仅将数字保存到新的文本文件中).
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
我已经尝试这个问题几个小时了,我有下面写的内容.
I have been attempting this problem for hours, and I have what is written below.
我不知道为什么我的代码似乎没有正确总结.
I do not know why my code does not seem to be summing up properly.
还有python代码:
And the python code:
f=open("C:\Users\Emily\Documents\not_just_numbers.txt", "r")
s=f.readlines()
p=str(s)
for line in s:
printnum=0
try:
printnum+=float(line)
print("Adding:", printnum)
except ValueError:
print("Invalid Literal for Int() With Base 10:", ValueError)
for line in s:
if p.isdigit():
total=0
for number in s:
total+=int(number)
print("The sum is:", total)
解决方案
我有一个代码,它依赖于我读取文本文件,打印出有数字的数字,打印出特定的错误消息其中有字符串而不是数字,然后将所有数字起来并打印它们的总和(然后只将数字保存到新的文本文件).
I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).
所以你必须做到以下几点:
So you have to do the following:
- 打印数字
- 当没有数字时打印一条消息
- 将数字相加并打印出总和
- 仅将数字保存到新文件中
这是一种方法:
total = 0
with open('input.txt', 'r') as inp, open('output.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))
相关文章