[英]How to Delete Subsequent Line After A Line With Specific Keyword in Python
After finding a specific line with keyword "banana", I would like to delete the subsequent line, in this case, "berry". 找到带有关键字“ banana”的特定行后,我想删除下一行,在这种情况下为“ berry”。
Sample.txt 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: 像这样做:
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) 这利用了
fin
对象的迭代,因此它不会看到下一行-这意味着您不必担心设置/取消设置标志...(这可能会导致错误)
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
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,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.