0

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?

Baba
  • 94,024
  • 28
  • 166
  • 217
Bruno Balas
  • 21
  • 1
  • 1
  • 2

1 Answers1

2

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'))
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Frerich Raabe
  • 90,689
  • 19
  • 115
  • 207
  • 5
    Interestingly, your concern about memory use could be addressed by simplifying your first suggestion: `sum(int(s) for s in open('foo.txt'))`. int will ignore trailing space for you, open files are iterable directly, and using a generator expression instead of a list comprehension will avoid another list. – Ned Batchelder Feb 09 '13 at 20:47
  • @NedBatchelder: Ah, that's good to know! You should've made your comment a separate answer so that it can be accepted - it's certainly better than mine. I guess it doesn't matter, now that this question has been closed. – Frerich Raabe Feb 10 '13 at 22:46