如何让这个停止?

时间:2014-03-10 22:45:17

标签: python

现在,它会读取一个txt文件并给出每行的总和。问题是它会在我的txt文件中打印每行数字的一行(所以说我的txt文件有25个不同的数字,它将打印“累计总数为:”25次,将最后一个值添加到下一个。我只想打印总数(一行)。这是作业作业。

def main ():
    print()
    print("This will add together the numbers on number.txt")
    print()
    total, error = getsum()

    if not error:
        total = getsum()
        print ("The sum is", total)

def getsum ():
    error = False
    total = 0
    try:
        infile = open("Numbers.txt", "r")
        line = infile.readline()

        while line != "":
            readnum = float(line)
            total = readnum + total
            line = infile.readline()

        print("The accumulated total is", total)            

       file.close()

    except IOError:
        print ("ERROR")
        error = True
    except ValueError:
        print ("ERROR")
        error = True

    if error:
        sum5 = 0
    else:
        sum5 = total
    return total, error, thesum

main ()

1 个答案:

答案 0 :(得分:1)

print sum(map(float,filter(lambda line:line.strip(),open("some.txt"))))

要短得多......或者如果您担心不关闭文件

with open("some.txt") as f:
     print sum(map(float,filter(lambda line:line.strip(),f)))