如何只读取文件中每隔一行的内容?

4

我需要读取一个非常大的文件中每隔一行的内容,因此不想使用readlines()。我不确定如何实现迭代器,欢迎任何建议。一种可能性是调用两次next(),但这并不是很理想。

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

或者创建自己的迭代器,例如:

for i, row in enumerate(pth):
    if i...

实际上,在那个循环中,你只需要调用一次 pth.next,因为循环本身也在每次迭代时读取一行。 - Karl Knechtel
嗯,没错。事实上我需要读取每三行。 - LarsVegas
2个回答

8

使用 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

哦,看起来很有前途。 - LarsVegas

1
你可以使用自定义迭代器:
def iterate(pth):
    for i, line in enumerate(pth, 1):
        if not i % 2:
            yield line

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接