Skip to content Skip to sidebar Skip to footer

File Operation Starts Again From First While Looping Through The File

I'm trying to find a certain word in a file and want to print the next line when a condition is met. f = open('/path/to/file.txt','r') lines = f.readlines() for line in lines:

Solution 1:

list.index() with just one argument only finds the first occurrence. You'd have to give it a starting point to find elements past the previous index, list.index() takes a second argument that tells it where to start searching from.

However, you don't need to use lines.index(); that's very inefficient; it requires a full scan through the list, testing each line until a match is found.

Just use the enumerate() function to add indices as you loop:

for index, line in enumerate(lines):
    if'P/E'in line:
        print(lines[index + 1])

Be careful, there is a chance index + 1 is not a valid index; if you find 'P/E' in the very last line of the lines list you'll get an IndexError. You may have to add a and index + 1 < len(lines) test.

Note that using file.readlines() reads all of the file into memory in one go. Try to avoid this; you could loop directly over the file, and remember the previous line instead:

withopen('/path/to/file.txt','r') as f:
    previous = ''for line in f:
        if'P/E'in previous:
            print(line)  # print this line
        previous = line  # remember for the next iteration

Post a Comment for "File Operation Starts Again From First While Looping Through The File"