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

时间:2023-01-02
本文介绍了如何在 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 中对文本文件中的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:什么是类似于 sum() 的减法函数,用于减去列表中 下一篇:列表字典中的总和值

相关文章

最新文章