How to select every other line from a text file?

Tim Chase python.list at
Mon Oct 13 19:55:55 CEST 2014

On 2014-10-13 10:38, Rff wrote:
> Hi,
> I have a text file. Now it is required to select every other line
> of that text to generate a new text file. I have read through
> Python grammar, but still lack the idea at the beginning of the
> task. Could you tell me some methods to get this?

You could force a re-read from the file each line:

  with open("x.txt") as f:
    for line in f:
      next(f)  # discard/consume the next line

Or, if you have it read into memory already, you could use slicing
with a stride of 2:

  with open("x.txt") as f:
    data = f.readlines()
    interesting = data[::2] # start with the 1st line
    # interesting = data[1::2] # start with the 2nd line

Or, if the file was large and you didn't want to have it all in
memory at the same time, you could use itertools.islice()

  from itertools import islice
  with open("x.txt") as f:
    interesting = islice(f, 0, None, 2) # start with 1st line
    #interesting = islice(f, 1, None, 2) # start with 2nd line

Note that in the last one, you get an iterator back, so you'd have to
either turn it into a list or iterate over it.


More information about the Python-list mailing list