python learner
python learner

Reputation: 13

How to print the line that appears before found line

I am trying to print certain lines from a text file which is essentially like a web page source code. One particular text is repeated several times and I want to print the line that appears before it.

Example to explain it:

.
.
text1
text
.
.
text2
text
.
.
text3
text
.
.

Expected output:

text1
text2
text3

My code:

import re
hand = open('sample.txt')
for line in hand:
    line = line.rstrip()
    if re.search('text', line):
        print(line)

This code gives me the line text but I want the line above it. I want to solve this using regex preferably.

Upvotes: 1

Views: 544

Answers (2)

Leo Arad
Leo Arad

Reputation: 4472

You can do it by a few options:

To find all lines before the text line with Positive Lookahead of regex

print(re.findall("(?=text\S).*", hand))

Output

['text1', 'text2', 'text3']

Or to get the previous line that you find a match with regex and enumerate

for index, line in enumerate(hand):
    line = line.rstrip()
    if re.search('text\b', line):
        print(hand[index -1])

Output

text1
text2
text3

Upvotes: 3

Fedor Soldatkin
Fedor Soldatkin

Reputation: 1203

hand = open('sample.txt')

prev_line = ''

for line in hand:
    line = line.rstrip()

    if 'text' in line:  # or if line == 'text'
        print(prev_line)

    prev_line = line

Upvotes: 1

Related Questions