After finding a specific line with keyword “banana”, I would like to delete the subsequent line, in this case, “berry”.
Sample.txt
orange
apple
banana
berry
melon
My script, however, deletes “banana” not “berry”….Why?
import fileinput
filename = r"C:\sample.txt"
for linenum,line in enumerate(fileinput.FileInput(filename, inplace=1)):
if "banana" in line:
counter = linenum + 1
if linenum == counter:
line.strip()
else:
print line,
Do it like this:
This takes advantage of iterating the
finobject so it doesn’t see the next row – meaning you don’t have to worry about setting/unsetting flags… (which can lead to errors)