在 Python 3 中找到特定行后如何跳过 n 行?
Posted
技术标签:
【中文标题】在 Python 3 中找到特定行后如何跳过 n 行?【英文标题】:How to skip n number of lines after finding a specific line in Python 3? 【发布时间】:2020-03-09 13:41:55 【问题描述】:假设我有一个大文本文件,我想跳过包含某个关键字的行以及该行之后的 2 行。
原始文件:
line1 some words
line2 some words
line3 keyword
line4 some words
line5 some words
line6 some words
line7 some words
line8 some words
新文件:
line1 some words
line2 some words
line6 some words
line7 some words
line8 some words
我的代码的简化 sn-p:
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
for line in lines:
if 'keyword' in line:
for i in range(3): continue
else:
nf.write(line + "\n")
循环“for i in range(3): continue”不会跳过行(我假设是因为它只是在嵌套的 for 循环中继续,而不是“for line in lines”for 循环。我也试过“ next(f)" 而不是 "continue" 并收到 StopIteration 错误消息。
当然,如果我尝试,
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
for line in lines:
if 'keyword' in line:
continue
else:
nf.write(line + "\n")
它成功跳过了一行,但只跳过了带有关键字的行,而我也想跳过接下来的两行(总共3行)。
感谢任何建议。感谢您的帮助。
【问题讨论】:
您可以使用索引来迭代for i in range(0, len(lines)):
,而不是迭代for line in lines:
,然后您可以随时增加索引(注意不要通过最后一行!)。
【参考方案1】:
您可以尝试迭代索引而不是元素:
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
i = 0
while i< len(lines):
line = lines[i]
if 'keyword' in line:
i+=3
else:
nf.write(line + "\n")
i+=1
【讨论】:
【参考方案2】:制作一个计数器并据此跳过行。
with open('Original_file','r') as f:
lines = f.readlines()
nf = open('New_file', 'w')
skip_lines = 0
for line in lines:
if skip_lines > 0:
skip_lines -= 1
elif 'keyword' in line:
skip_lines = 3
else:
nf.write(line + "\n")
【讨论】:
【参考方案3】:您可以使用标志 /counter 来实现此目的
with open('Original_file','r') as f:
lines = f.readlines()
skip = 0
nf = open('New_file', 'w')
for line in lines:
if skip:
skip -=1
elif 'keyword' in line:
skip = 3
else:
nf.write(line + "\n")
【讨论】:
【参考方案4】:问题是您直接从列表中提取行,因此,您无法与for line in lines
使用的底层迭代器进行交互。
您应该简单地将文件对象用作迭代器:
with open('Original_file','r') as f, open('New_file', 'w') as nf
for line in f:
if 'keyword' in line:
for i in range(2): next(f)
else:
nf.write(line)
这里唯一的假设是任何包含keyword
的行后面至少有2 行。
【讨论】:
【参考方案5】:你可以使用next()
,即:
with open("old.txt") as f, open("new.txt", "w") as w:
for line in f:
if "keyword" in line:
next(f), next(f)
continue
w.write(line)
Demo
如果你喜欢list comprehension,你也可以使用:
with open("old.txt") as f, open("new.txt", "w") as w:
[w.write(line) if not "keyword" in line else [next(f) for _ in range(2)] for line in f]
Demo
【讨论】:
以上是关于在 Python 3 中找到特定行后如何跳过 n 行?的主要内容,如果未能解决你的问题,请参考以下文章
删除特定行后如何修改数据库 phpmyadmin 中的主键?
如何跳过 ARIMA 模型(python)中的第一个滞后 N 天?