如何在 Python 中对文本文件中的数字求和

How to sum numbers from a text file in Python(如何在 Python 中对文本文件中的数字求和)
本文介绍了如何在 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:

  1. 打印数字
  2. 当没有数字时打印一条消息
  3. 将数字相加并打印出总和
  4. 仅将数字保存到新文件中

这是一种方法:

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))

这篇关于如何在 Python 中对文本文件中的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)