在逐行读取文件时生成总和

时间:2018-02-09 15:00:25

标签: python sum

我在逐行读取文件时生成一些数字的总和有些麻烦。我想从单独的文件计算总和而不将数字保存为列表。对此有简单的命令吗?我的代码如下所示:

def imput(filename):
    with open(filename, 'r') as f: #open the file
        for line in f:
            input('sample.txt')`

文件'sample.txt'由数字1,2,4,6,8组成,当我使用print函数时,我得到:

print(line)

1

2

4

6

8

1 个答案:

答案 0 :(得分:1)

您可以使用sum()总数,例如:

代码:

  <input *ngIf (focusout)="childtitle.val != '' ? save() : '' " >

如果你喜欢map()的简洁性,可以缩短为:

total = sum(int(line) for line in open('file1', 'rU'))
print(total)

结果:

total = sum(map(int, open('file1', 'rU')))