简体   繁体   中英

remove specific lines if some specific word is found

Lets say I have a text file that contains following words

a
b
c
d
e>
f
g
h
I>
j

whenever I find a words that contains > , I would like to replace the last two lines from it and itself too.

For example, the output would be this.

a
b
f
j

Is it possible to achieve this ?. For simple replace, I can do this

with open ('Final.txt', 'w') as f2:
    with open('initial.txt', 'r') as f1:
        for line in f1:
            f2.write(line.replace('>', ''))

But I am stuck on how do I go back and delete the last two lines and also the line where the replace happen.

This is one approach using a simple iteration and list slicing.

Ex:

res = []
with open('initial.txt') as infile:
    for line in infile:
        if ">" in line:
            res = res[:-2]
        else:
            res.append(line)

with open('Final.txt', "w") as f2:
    for line in res:
        f2.write(line)

Output:

a
b
f
j

Use re . Here I am assuming that your data is a flat list of lines.

import re
print(re.sub('.*\n.*\n.*>\n','',''.join(data)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM