Naveen
Naveen

Reputation: 475

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:
    if 'P/E' in line:
        n = lines.index(line) #get index of current line
        print(lines[n+1])     #print the next line
a.close()

The string 'P/E' will be present 4 times in the file, each time in a different line.

When executed, the code prints the next line after the first 2 occurrences of 'P/E' normally. It then again goes back and prints the same first 2 occurrences again and exits. The loop is not proceeding after those first 2 occurrences; it kind of repeats the process and exits.

I checked the data file to see if my output is the actual result, but all next lines are different after 'P/E'.

How can I resolve this? Thanks.

Upvotes: 0

Views: 53

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

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:

with open('/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

Upvotes: 2

Related Questions