2

Im trying to loop through a number of N rows at a time in a text file . How do I loop through the whole file for instance say it has 100 rows and print 10 at a time. This is how far I got.

 N=10
 f=open("data.txt")
 for i in range(N):
     line=f.next().strip()
     print line
 f.close()
BKCapri
  • 548
  • 2
  • 8
  • 21

1 Answers1

5

You could treat the file as an iterator and just take extra items from it on each iteration:

with open('data.txt') as f:
    for line in f:
        lines = [line] + [next(f) for _ in xrange(9)]  # have 1 already, so need 9
        # process lines

If your file length is not divisible by your chunk size, you can use next(f, None) instead, and filter out the Nones before processing lines.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 1
    This will raise a `StopIteration` error (at least in Python 3) if the line count is not divisible by the step... – brianpck Dec 22 '16 at 18:47
  • 1
    @brianpck You can use `next(f, None)` in that case. I updated the answer to reflect that. – arshajii Dec 22 '16 at 18:49
  • @BKCapri - to remove the newlines: `lines = [line.strip() for line in lines]` – Robᵩ Dec 22 '16 at 19:00
  • @arshajii - Perhaps `lines = [line] + list(iterator.islice(f, 0, 9))`. That might solve the not-evenly-divisible problem. – Robᵩ Dec 22 '16 at 19:02