如何在Python中对文本文件中的数字求和 [英] How to sum numbers from a text file in Python

查看:916
本文介绍了如何在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中对文本文件中的数字求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆