Preetham CS
Preetham CS

Reputation: 51

How can i pass a line number in a for loop to traverse a text file?

I have a text file in which i want to start doing a task only after i find a keyword. But the keyword I'm searching for occurs twice in the file. I want to do the task only for the text after second keyword.

I can get the line in which my required keyword occurs second time but how do i pass this to a for loop and do my task.

Im looking for something like:

with open(r"myfile.txt") as openfile:
    for line in (line_number, openfile):
        #Do my task to the line

Where line_number has the number where I found the keyword second time

Upvotes: 0

Views: 757

Answers (2)

blackraven
blackraven

Reputation: 5597

You could use a simple flag count to determine the second time the keyword is found:

keyword = 'A'
with open('test.txt') as fp:
    c, flag = 0, 0
    while True:
        line = fp.readline()
        if not line:
            break
        c += 1
        print("Line {}: {}".format(c, line.strip()))
        if keyword in line:
            flag += 1
        if keyword in line and flag == 2:
            print('do some tasks')

Output

Line 1: C E
Line 2: A F
Line 3: E
Line 4: C D
Line 5: A B
do some tasks
Line 6: 1 C E

A better approach (same output) would be to use enumerate:

keyword = 'A'
with open('test.txt') as fp:
    flag = 0
    for c, line in enumerate(fp):
        print("Line {}: {}".format(c+1, line.strip()))   #remove whitespace characters like `\n` at the end of each line
        if keyword in line:
            flag += 1
        if keyword in line and flag == 2:
            print('do some tasks')

Upvotes: 1

blhsing
blhsing

Reputation: 106703

If you want to process only the lines after the line with the second occurrence of a keyword, you should not be looking for line numbers. Instead, you can treat the file object as an iterator and use a generator expression to filter lines with the keyword and use itertools.islice to consume lines up to the line with the second occurrence of the keyword.

As an example, the code below skips lines until the second occurrence of the keyword begin:

from itertools import islice

keyword='begin'
with open('myfile.txt') as openfile:
    list(islice((line for line in openfile if keyword in line), 0, 2))
    for line in openfile:
        print(line, end='')

so that given the content of myfile.txt:

header
begin
second header
begin
foo
bar

the above code would output:

foo
bar

Demo: https://replit.com/@blhsing/OnlyUtterFossil

Upvotes: 1

Related Questions