使用for循环从.txt文件中添加数字总和

时间:2015-11-25 15:34:38

标签: for-loop python-3.4 readfile accumulator

我尝试添加文本文件中所有数字的总和,然后打印出添加的所有数字。 文本文件包括9,5,9,7,11。数字在不同的行上。总数是41,但我的代码保持打印52 输出应如下所示: 9 5 9 7 11.你的总数是:41

    def main():
    # Open a file for reading.
    infile = open('numbers.txt', 'r')




    total = 0
    for line in infile:
        amount = int(line)
        total += amount








    total += int(line.strip())




    infile.close()




    print(line)
    print('Your total is:',total)







main()

1 个答案:

答案 0 :(得分:0)

infile = open('numbers.txt', 'r')
total = 0
for line in infile:
    amount = int(line)
    total += amount
infile.close()
print(line)
print('Your total is:',total)

无需使用此行

total += int(line.strip())

现在您的程序正常运行。