![](/img/trans.png)
[英]If the next line of a file contains a string, append it to the end of the current one
[英]How to print the next line from a file, if current line contains a string?
我正在嘗試編寫一些東西來打印文件中的某些行。 假設文件如下所示:
name = 1
name = a
name = 2
name = b
name = 3
extra = 1
name = c
name = 4
extra = 1
name = d
所以通常我可以這樣做if line startswith(name)
並將它們全部打印出來,但是假設我只需要以“name”開頭的行,它們位於以“extra”開頭的行之后。 但我不知道如何打印line + 1
之類的東西。 如何根據上一行的內容打印下一行?
在輸入處理循環的最后,保留當前輸入行的副本,並將其命名為previous_line
。 然后,在下一次迭代中,您將可以訪問當前輸入行和上一個輸入行。
previous_line = ''
for line in f:
if line.startswith('name') and previous_line.startswith('extra'):
print line
# keep a copy of this line for the next loop
previous_line = line
您可以簡單地使用布爾值標志並僅在設置了標志的情況下進行打印。 就像是:
print_next_line = False
for line in f_in:
if print_next_line:
print(line)
print_next_line = False
else:
print_next_line = line.startswith()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.