2014-05-10 99 views
0

以下是我到目前爲止:我知道在將數量更改爲浮點數後,我需要將文件numberGood.txt中的數字總和,但數字沒有變量名稱,即。 num1,num2,因爲程序不知道文件的數量。我用while循環解決了這個問題,但是如何獲得所有數字的總和?Python - 從文本文件求和變量

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

回答

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