Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in only every second line of file?

I need to read in only every second line of a file (which is very big) so I don't want to use readlines(). I'm unsure how to implement the iterator so any suggestions are welcome. One possibility is to call next() twice. Not very appealing.

    with open(pth_file, 'rw') as pth:
        pth.next()
        for i,row in enumerate(pth):
            # do stuff with row
            pth.next()

Or creating my own iterator like

for i, row in enumerate(pth):
    if i...
like image 677
LarsVegas Avatar asked Jan 12 '23 07:01

LarsVegas


1 Answers

Using itertools.islice:

import itertools

with open(pth_file) as f:
    for line in itertools.islice(f, 1, None, 2):
        # 1: from the second line ([1])
        # None: to the end
        # 2: step

        # Do something with the line
like image 160
falsetru Avatar answered Jan 21 '23 10:01

falsetru