Reputation: 1175
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,
Upvotes: 0
Views: 3198
Reputation: 142206
Do it like this:
import fileinput
fin = fileinput.input('/home/jon/text.txt', inplace=1)
for line in fin:
print line,
if line.strip() == 'banana':
next(fin, None) # as suggested by @thg435 doesn't hurt to use default to avoid StopIteration (as next iteration will just be a no-op anyway)
This takes advantage of iterating the fin
object so it doesn't see the next row - meaning you don't have to worry about setting/unsetting flags... (which can lead to errors)
Upvotes: 3
Reputation: 5022
Something like this:
flag = False
with open("C:\sample.txt") as in_f:
for line in in_f:
if flag: # previous line have "banana", so skip this line
flag = False
continue
if "banana" in line: # set flag to skip line
flag = True
print line
Upvotes: 2
Reputation: 369
Please try this
filename = r"sample.txt"
counter = -1
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,
Upvotes: 1