我试图编写一个代码来查找文件中的特定文本并获取该行。
f = open('programa.txt','r')
for line in f:
if (line == "[Height of the board]\n"):
## skip to next line and saves its content
print(line)
答案 0 :(得分:1)
设置一个标志,以便你知道如何抓住下一行。
f = open('programa.txt','r')
grab_next = False
for line in f:
if grab_next:
print(line)
grab_next = line == "[Height of the board]\n"
答案 1 :(得分:1)
文件对象是Python中的迭代器;当for
循环隐式使用迭代器协议时,您可以在需要跳过时自己手动调用它:
with open('programa.txt') as f:
for line in f:
if line == "[Height of the board]\n":
# skip to next line and saves its content
line = next(f)
print(line)
存储下一行的示例代码不清楚,因此我将其存储回line
,使原始行标题消失。如果目标是仅打印该行并中断,则可以使用:
with open('programa.txt') as f:
for line in f:
if line == "[Height of the board]\n":
# skip to next line and saves its content
importantline = next(f)
print(importantline)
break
答案 2 :(得分:1)
当你回顾而不是试图向前看时,这样的问题几乎总是更简单。毕竟,找出最后一行是微不足道的;你只需将它存储在变量中!在这种情况下,如果上一个行是标题,则要保存当前行:
access