How to sum numbers from text file in python? Let's say that we have some text document that have numbers like this:
320
5203
5246
And we want python open that file and sum those numbers to get to the result: 10769. How shall I do this?
How to sum numbers from text file in python? Let's say that we have some text document that have numbers like this:
320
5203
5246
And we want python open that file and sum those numbers to get to the result: 10769. How shall I do this?
If the file is not too big, you can just read the file into an array, use a list comprehension to convert the lines into a list of integers and then compute the sum of that:
sum([int(s.strip()) for s in open('foo.txt').readlines()])
However, this reads the entire file into memory. If your file is large it would probably be less memory-intensive to accumulate the sum in an imperative manner:
result = 0
for s in open('foo.txt'): result += int(s.strip())
Or as a generator expression so that a list does not need to be stored in-memory
sum(int(s.strip()) for s in open('foo.txt'))