如何在Python中打印下一行 [英] How to print next line in python
问题描述
我试图在比赛结束后打印下3行
例如输入是$ $ p
测试
结果
test1:12345
test2:23453
test3:2345454
所以我试图在文件中搜索结果字符串,然后打印下面3行:
输出结果为:
test1:12345
test2 :23453
test3:2345454
我的代码是:
与开放(文件名,'r +')作为f:
用于f:
打印行
如果基准结果in f:
print f
print next(f)
只给我输出:
测试
我如何得到我想要的输出,请帮助解决方案
首先,您需要检查该文本是在 line
(不在fileobj f
中),您可以使用 islice
从 f
取下3行并打印出来,例如:
b
$ '.join(islice(f,3)))
循环将从三印。如果你不想要的话 - 如果中有 I am trying to print next 3 lines after a match for example input is : so i am trying to search "Result" string in file and print next 3 lines from it: Output will be :- my code is : its only giving me the output : how do i get my desired output, help please First you need to check that the text is in the The loop will continue from the line after the three printed. If you don't want that - put a 这篇关于如何在Python中打印下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! break
,那么在中加入
Testing
Result
test1 : 12345
test2 : 23453
test3 : 2345454
test1 : 12345
test2 : 23453
test3 : 2345454
with open(filename, 'r+') as f:
for line in f:
print line
if "Benchmark Results" in f:
print f
print next(f)
testing
line
(not in the fileobj f
), and you can utilise islice
to take the next 3 lines from f
and print them, eg:from itertools import islice
with open(filename) as f:
for line in f:
if 'Result' in line:
print(''.join(islice(f, 3)))
break
inside the if
.