1

I'm trying to read the rest of a file after finding a word.

I'm trying to write a program that searches for a word in a file and then, when the word was found, it needs to do something with the remaining lines that are below / after the word.

Here's what I have so far but it's not working. Please assist. thanks.

def readFile():
    with open(“file.txt”, "r") as file:
        for line in file:
            if “Hello” in line:
                break
        nextline = file.readlines()
        for line in nextline 
            print(line)
avenet
  • 2,894
  • 1
  • 19
  • 26
Smock
  • 345
  • 1
  • 2
  • 10

1 Answers1

3

You can't mix iteration (which basically calls the file.next method in the loop) and readlines.

To quote a great man (and file.next documentation):

In order to make a for loop the most efficient way of looping over the lines of a file (a very common operation), the next() method uses a hidden read-ahead buffer. As a consequence of using a read-ahead buffer, combining next() with other file methods (like readline()) does not work right

You can do fine with using just iteration:

def readFile():
    with open("file.txt", "r") as file:
        for line in file:
            if "Hello" in line:
                break
        for line in file:
            # do something with the line
Nigel Tufnel
  • 11,146
  • 4
  • 35
  • 31