简体   繁体   中英

How I can read the next line in a for loop? Python

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 .

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)

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM