如何只读取文件的第二行?


问题内容

我只需要读文件的第二行(很大),所以我不想使用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...

问题答案:

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