python - Sum of all numbers in a file -


i have been fiddling round code ages , cannot figure out how make pass doctests. output 1000 less corrects answer. there simple way change code gives desired output ?? code is:

def sum_numbers_in_file(filename):     """     return sum of numbers in given file (which contains     integers separated whitespace).     >>> sum_numbers_in_file("numb.txt")     19138     """     f = open(filename)     m = f.readline()     n = sum([sum([int(x) x in line.split()]) line in f])     f.close()     return n 

the values in file are:

1000  15000  2000  1138 

the culprit is:

m = f.readline()  

when doing f.readline(), losing 1000, not being considered in list comprehension. hence error.

this should work:

def sum_numbers_in_file(filename):     """     return sum of numbers in given file (which contains     integers separated whitespace).     >>> sum_numbers_in_file("numb.txt")     19138     """     f = open(filename, 'r+')     m = f.readlines()     n = sum([sum([int(x) x in line.split()]) line in m])     f.close()     return n 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -