starshine starshine - 2 years ago 101
Python Question

print next line only if it begins with a specific word

I am a bit new to python and I was wondering if anyone can help. Basically I am reading contents of a file and when I find the word "prb" I want to check the next line using the next() function and if it starts with the word "rt", i want to print both lines. So far I wrote this piece of code:

with open('/home/user/Desktop/3rdstep.txt', 'r') as f:
for line in f:
if "prb" in line:
myword = next(f)
if "rt" in myword:

This works fine but the only problem is that it skips randomly "rt" words for a reason I don't know. Can anyone help please or have someone done something similar?


Answer Source

If your input has two consecutive lines starting with 'prb' followed by line starting with 'rt' then they are skipped. The only exception is the case where they are the first three lines in the file. This is because for line in f: reads the first line starting with 'prb' and myword = next(f) reads the second line. Thus on the following iteration line starts with 'rt'.

Instead of reading the next line you could store the previous line and then check if two lines match:

prev = ''
with open('/home/user/Desktop/3rdstep.txt') as f:
    for line in f:
        if prev.startswith('prb') and line.startswith('rt'):
        prev = line
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download