How to read in only every second line of file?

前端 未结 2 1263
感情败类
感情败类 2021-01-06 05:26

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 sug

相关标签:
2条回答
  • 2021-01-06 05:54

    You can use a custom iterator:

    def iterate(pth):
        for i, line in enumerate(pth, 1):
            if not i % 2:
                yield line
    
    0 讨论(0)
  • 2021-01-06 06:09

    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
    
    0 讨论(0)
提交回复
热议问题