0

I have a for loop iterating through my file, and based on a condition, I want to be able to read the next line in the file.I want to detect a keyword of [FOR_EACH_NAME] once I find it, I know that names will follow and I print each name. Basically Once I find the [FOR_EACH_NAME] keyword how can I keep going through the lines.

Python code:

file=open("file.txt","r")

for line in file:
    if "[FOR_EACH_NAME]" in line
        for x in range(0,5)
            if "Name" in line:
                print(line)

Hi everyone, thank you for the answers. I have posted the questions with much more detial of what I'm actually doing here How to keep track of lines in a file python.

2
  • You can use next(file) to get the next line. Note that in doing this, you're advancing the same iterator as your for loop is using, so it will miss any lines you get in this way. Commented Oct 27, 2015 at 20:57
  • The only catch to this is the code fails once the file's swapped out for a list. Commented Oct 27, 2015 at 21:01

3 Answers 3

2

Once you found the tag, just break from the loop and start reading names, it will continue reading from the position where you interrupted:

for line in file:
    if '[FOR_EACH_NAME]' in line:
        break
else:
    raise Exception('Did not find names')  # could not resist using for-else

for _ in range(5):
    line = file.readline()
    if 'Name' in line:
        print(line)
Sign up to request clarification or add additional context in comments.

1 Comment

The OP didn't specify that he wanted to find only one list of names. Nice For-Else though!
0

Are the names in the lines following FOR_EACH_NAME? if so, you can check what to look for in an extra variable:

file=open("file.txt","r")

names = 0
for line in file:
    if "[FOR_EACH_NAME]" in line
        names = 5
    elif names > 0:
        if "Name" in line:
            print(line)
        names -= 1

Comments

0

I think this will do what you want. This will read the next 5 lines and not the next 5 names. If you want the next five names then indent once the line ct+=1

#Open the file
ffile=open('testfile','r')

#Initialize
flg=False
ct=0

#Start iterating
for line in ffile:
    if "[FOR_EACH_NAME]" in line:
        flg=True
        ct=0
    if "Name" in line and flg and ct<5:
        print(line)
    ct+=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.