Search code examples
pythontext-processing

How to access next line in a file(.txt) in Python


I have a file and I open it and then I check for few things. If the line starts with "E PARAM" and also has "OOPS1" in it somewhere then I want to check that the next line starts with " E PARAM". If not I will make a new file and copy it there till the time I dont hit another "E PARAM" line. Since Python doesnt have a next() option... what can help me here

import string
import os


A = "k_trap_cur"
B = open(A, 'r+')
lines = B.readline()

for lines in B:
    if lines.startswith("E PRAM"):
        if "OOPS: 1" in lines:
            while lines.next().startswith("E PARAM") == False: // HERE I want to access next line
                print " YES"

Solution

  • If I understood you right:

    b = open(a, 'r+')
    for line in b:
        if line.startswith("E PRAM") and "OOPS: 1" in line:
            next_line = next(b)
            # do whatever you need
    

    Files provide what is called an “Iterator protocol” and that's why they work in for-loops. You can also call next function on them manually, if you want. Check PEP-234 for more details.