在 Python 中遍历从文件读取的行时如何跳到下一个元素?
How to skip to the next element when iterating over lines read from a file, in Python?
我正在尝试编写一个代码来查找文件中的特定文本并获取后面的行。
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)
设置一个标志,以便您知道抓取下一行。
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"
文件objects是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
,使原始行 header 消失。如果目标是仅打印该行并打断,您可以使用:
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
当您回顾而不是试图展望未来时,这样的问题几乎总是更简单。毕竟,找出最后一个线是微不足道的;你只需将它存储在一个变量中!在这种情况下,如果 previous 行是 header:
,则您想保存 current 行
f = open('programa.txt', 'r')
last = ""
for line in f:
if last == "[Height of the board]\n":
height = int(line.strip()) # for example
break # exit the loop once found (optional)
last = line
我正在尝试编写一个代码来查找文件中的特定文本并获取后面的行。
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)
设置一个标志,以便您知道抓取下一行。
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"
文件objects是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
,使原始行 header 消失。如果目标是仅打印该行并打断,您可以使用:
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
当您回顾而不是试图展望未来时,这样的问题几乎总是更简单。毕竟,找出最后一个线是微不足道的;你只需将它存储在一个变量中!在这种情况下,如果 previous 行是 header:
,则您想保存 current 行f = open('programa.txt', 'r')
last = ""
for line in f:
if last == "[Height of the board]\n":
height = int(line.strip()) # for example
break # exit the loop once found (optional)
last = line