如何在Python中打印下一行 [英] How to print next line in python

查看:1479
本文介绍了如何在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)))

循环将从三印。如果你不想要的话 - 如果中有 break ,那么在中加入

I am trying to print next 3 lines after a match

for example input is :

Testing
Result
test1 : 12345
test2 : 23453
test3 : 2345454

so i am trying to search "Result" string in file and print next 3 lines from it:

Output will be :-

test1 : 12345
test2 : 23453
test3 : 2345454

my code is :

with open(filename, 'r+') as f:
    for line in f:
        print line
        if "Benchmark Results" in f:
            print f
            print next(f)

its only giving me the output :

testing

how do i get my desired output, help please

解决方案

First you need to check that the text is in the 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)))

The loop will continue from the line after the three printed. If you don't want that - put a break inside the if.

这篇关于如何在Python中打印下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆