Python - 来自文本文件的sum变量

时间:2014-05-10 01:46:41

标签: python variables while-loop sum

以下是我到目前为止的情况:我知道在将金额更改为浮点数后,我需要将文件numberGood.txt中的数字相加,但数字不具有变量名称,即。 num1,num2,因为程序不知道文件数。我用while循环解决了这个问题,但是如何得到所有数字的总和呢?

* numberGood.txt是我需要在程序中求和的各种整数的列表。

如果有人能够解释和/或给我一个例子,我将非常感激。

def main(): 
    goodNum = open("numberGood.txt",'r')
    input("Enter file name.")
    line = goodNum.readline()
    while line != "":
    amount = float(line)
    print(format(amount, '.1f'))
    line = goodNum.readline()
    print("The total is: ", amount)
    goodNum.close()
main()

2 个答案:

答案 0 :(得分:0)

使用sum()

with open("numberGood.txt") as f:
    print(sum(float(line) for line in f))

演示:

$ cat numberGood.txt 
10.01
19.99
30.0
40
$ python3
>>> with open("numberGood.txt") as f:
...     print(sum(float(line) for line in f))
... 
100.0

答案 1 :(得分:0)

您可以将它们添加到列表中,然后按如下方式返回列表总和:

def main(): 
    goodNum = open("numberGood.txt",'r')
    lst = []
    for line in goodNum:
        lst.append(float(line))
        print(format(lst[-1], '.1f'))
    print("The total is: ", sum(lst))
    goodNum.close()

main()