Python: search and print lines in a file by increments of 2

2k views Asked by At

I am new so I hope this isn't redundant. Lets say I have an input file named "mccell" that looks like

     Initial Molecules:                 47
     Initial Molecules:                  1
       1          47
       1           1
       2          48
       2           0
       3          48
       3           0
       4          48
       4           0
       5          48
       5           0
       6          48
       6           0
       7          48
       7           0
       8          48
       8           0
       9          48
       9           0

I am trying to figure out how I would go about printing specific lines in increments that I specify. For example, how would I start at the line "Initial Molecule" and print ONLY the lines that are in increments of two after. To illustrate what I am describing what I want the code to do:

    Initial Molecules:                 47
    1          47
    2          48
    3          48
    4          48
    5          48
    6          48
    7          48
    8          48
    9           48

I have tried the readlines() function, but to no avail as I can only print the entire file. This is the incorrect code that I have:

    fo = open("mccell")
    lines = fo.readlines()
    print lines

Any help or tips would be appreciated. Thanks!

4

There are 4 answers

0
mfjones On

You can use a counter to keep track of the odd and even lines.

line_num = 0
with open('mccell') as f:
  for line in f:
    if line_num % 2 == 0:
       print line
    line_num += 1
0
Adam Smith On

You can use the next built-in function to advance an iterator manually.

with open('mccell') as f:
    alternating = False
    for line in f:
        print(line)
        if "Initial Molecules" in line:
            alternating = True
        if alternating:
            next(f)
            # if we've encountered "Initial Molecules", skip a line

It might be easier to read (but slower) to run through the list, find the starting line, then use file.seek and itertools.islice to run through the file again. This also allows you do change the increment much easier.

import itertools

INCREMENT = 2

with open('mccell') as f:
    for line_no, line in enumerate(f):
        if "Initial Molecules" in line:
            start = line_no
            break
    else:
        # there is no "Initial Molecules" in this file, handle it!
    f.seek(0)
    # put file pointer back at the start of the file
    for line in itertools.islice(f, start, None, INCREMENT):
        print(line)

N.B. that I never use f.readlines(), so I never build a list in memory of all the lines in the file. if your file is particularly large (or your target machine is particularly weak) this could be incredibly important. Also using the with block rather than fo = open('mccell'); ...; fo.close() means there's no chance of the file remaining open after you're done working with it and is an established best practice.

2
aadarshsg On
print lines[0::2]

Start from index 0. Jump 2 everytime.

1
Jagadesh Babu T On

You could use the range method to do the trick.

fo = open("mccell")
lines = fo.readlines()
print lines

Iterate over the lines, since lines are stored internally as a list object in python and you could use range ranging from 0 to len(lines) by 2 steps

for i in range(0, len(lines), 2):
    print lines[i]