I'm removing specific string and empty line in a text file and this is following to my earlier question... I refer to some examples and solution by our SO experts... and it work well by removing the string but not the empty line. To make it simple to understand i highlight the problem here.
Some part of the text file contain line of stringA, stringB and stringC and also empty line below it and only to delete single line below it.
line0
line1 stringAxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line2 stringBxxxxxxxxxxxxxxxxxxxxxxx
line3 stringCxxxxxxxxxxxxxxxxxxx
line4
line5
line6 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line7 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line8
line9 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line10 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line11 stringBxxxxxxxxxxxxxxxxxxxxxxx
line12 stringCxxxxxxxxxxxxxxxxxxx
line13
line14
line15 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line16 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line17
line18 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line19 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line20
line21 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line22 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line23
line24 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line25 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line26 stringBxxxxxxxxxxxxxxxxxxxxxxx
line27 stringCxxxxxxxxxxxxxxxxxxx
line28
line29
line30 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line31 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line32
In this case to remove any line that have any stringA, stringB, stringC and one line after it. For example above, remove line 1,2,3,4 remove line 11,12,13 remove line 26,27,28
I have tried using strip() but it remove all empty line. This is the script I use and it does remove all the line that contain stringA, stringB and stringC.
filename = 'raw.txt'
with open(filename, 'r') as fin:
lines = fin.readlines()
with open('clean.txt', 'w') as fout:
for line in lines:
if not re.match(r"\s+(stringA|stringB|stringC)", line):
fout.write(line)
expected output
line0
line5
line6 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line7 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line8
line9 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line10 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line14
line15 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line16 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line17
line18 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line19 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line20
line21 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line22 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line23
line24 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line25 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line29
line30 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line31 textxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
line32
Appreciate for your help and kind assistance. Thank you.