python - Read from file: read two lines, skip two lines -


i want read 2 lines file, skip next 2 lines , read next 2 lines , on

line 1 (read) line 2 (read) line 3 (skip) line 4 (skip) line 5 (read) line 6 (read) ... <eof> 

any ideas how this? thanks!

my solution:

            j = 2              i, line in enumerate(f.readlines()):                 if in xrange(j - 2, j):                     print line                 elif == j:                     j += 4 

you can advance iteration of file the itertools consume() recipe - fast (it uses itertools functions ensure iteration happens in low-level code, making process of consuming values fast, , avoids using memory storing consumed values):

from itertools import islice import collections  def consume(iterator, n):     "advance iterator n-steps ahead. if n none, consume entirely."     # use functions consume iterators @ c speed.     if n none:         # feed entire iterator zero-length deque         collections.deque(iterator, maxlen=0)     else:         # advance empty slice starting @ position n         next(islice(iterator, n, n), none) 

by doing this, can like:

with open("file.txt") file:     i, line in enumerate(file, 1):         ...         if not % 2:             consume(file, 2)  # skip 2 lines ahead. 

we use enumerate() count our progress, , skip ahead every 2 lines (note enumerate() adds numbers after values skipped, meaning doesn't count skipped values, wanted).

this solution avoids python looping @ skipped values, cutting them out completely.


Comments

Popular posts from this blog

curl - PHP fsockopen help required -

HTTP/1.0 407 Proxy Authentication Required PHP -

c# - Resource not found error -