Python – go to two lines above match – Education Career Blog

In a text file like this:

First Name last name #
secone name
Address Line 1
Address Line 2
Work Phone:
Home Phone:
Status:

First Name last name #
….same as above…

I need to match string ‘Work Phone:’ then go two lines up and insert character ‘|’ in the begining of line. so pseudo code would be:

if “Work Phone:” in line:
go up two lines:
write | + line
write rest of the lines.

File is about 10 mb and there are about 1000 paragraphs like this.
Then i need to write it to another file. So desired result would be:

First Name last name #
secone name
|Address Line 1
Address Line 2
Work Phone:
Home Phone:
Status:

thanks for any help.

,

This solution doesn’t read whole file into memory

p=""
q=""
for line in open("file"):
    line=line.rstrip()
    if "Work Phone" in line:
       p="|"+p
    if p: print p
    p,q=q,line
print p
print q

output

$ python test.py
First Name last name #
secone name
|Address Line 1
Address Line 2
Work Phone:
Home Phone:
Status:

,

You can use this regex

(.*\n){2}(Work Phone:)

and replace the matches with

|\1\2

You don’t even need Python, you can do such a thing in any modern text editor, like Vim.

,

Something like this?

lines = text.splitlines()
for i, line in enumerate(lines):
    if 'Work Phone:' in line:
        linesi-2 = '|' + linesi-2

Leave a Comment