How to read only in every second line of the file?

I need to read only every second line of the file (which is very large), so I do not want to use it readlines(). I'm not sure how to implement an iterator, so any suggestions are welcome. One possibility is to call next () twice. Not very attractive.

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

Or create your own iterator like

for i, row in enumerate(pth):
    if i...
+4
source share
2 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
+8
source

You can use a custom iterator:

def iterate(pth):
    for i, line in enumerate(pth, 1):
        if not i % 2:
            yield line
+1
source

Source: https://habr.com/ru/post/1525021/


All Articles