简体   繁体   中英

How to skip to the next element when iterating over lines read from a file, in Python?

I'm trying to write a code that looks for a specific text in a file and gets the line after.

f = open('programa.txt','r') 
for line in f:
    if (line == "[Height of the board]\n"):
      ## skip to next line and saves its content

    print(line)

Set a flag so you know to grab the next line.

f = open('programa.txt','r') 
grab_next = False
for line in f:
    if grab_next:
        print(line)
    grab_next = line == "[Height of the board]\n"

File objects are iterators in Python; while the for loop uses the iterator protocol implicitly, you can invoke it manually yourself when you need to skip ahead:

with open('programa.txt') as f:
    for line in f:
        if line == "[Height of the board]\n":
            # skip to next line and saves its content
            line = next(f)
        print(line)

Your example code is unclear on where to store the next line, so I've stored it back to line , making the original line header disappear. If the goal was to print only that line and break, you could use:

with open('programa.txt') as f:
    for line in f:
        if line == "[Height of the board]\n":
            # skip to next line and saves its content
            importantline = next(f)
            print(importantline)
            break

Problems like this are almost always simpler when you look back rather than trying to look ahead. After all, finding out the last line is trivial; you just store it in a variable! In this case, you want to save the current line if the previous line was the header:

f = open('programa.txt', 'r')
last = ""
for line in f:
    if last == "[Height of the board]\n":
        height = int(line.strip())    # for example
        break                         # exit the loop once found (optional)
    last = line

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