如何只读取每一行文件? [英] How to read in only every second line of file?

查看:207
本文介绍了如何只读取每一行文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只需要读取文件的每一行(非常大),所以我不想使用 readlines()。我不确定如何实现迭代器,所以欢迎任何建议。一种可能性是两次调用next()。不太吸引人。

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...


推荐答案

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

这篇关于如何只读取每一行文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆