Shi*_*pro 1 python file-io file filestream python-3.x
我试图在比赛后打印接下来的 3 行
例如输入是:
Testing
Result
test1 : 12345
test2 : 23453
test3 : 2345454
Run Code Online (Sandbox Code Playgroud)
所以我试图在文件中搜索“结果”字符串并从中打印下 3 行:
输出将是:-
test1 : 12345
test2 : 23453
test3 : 2345454
Run Code Online (Sandbox Code Playgroud)
我的代码是:
with open(filename, 'r+') as f:
for line in f:
print line
if "Benchmark Results" in f:
print f
print next(f)
Run Code Online (Sandbox Code Playgroud)
它只给我输出:
testing
Run Code Online (Sandbox Code Playgroud)
我如何获得我想要的输出,请帮忙
首先,您需要检查文本是否在line(不在 fileobj 中f),您可以利用islice从中取出接下来的 3 行f并打印它们,例如:
from itertools import islice
with open(filename) as f:
for line in f:
if 'Result' in line:
print(''.join(islice(f, 3)))
Run Code Online (Sandbox Code Playgroud)
循环将从打印三个之后的行开始。如果你不想那样 -break在if.
| 归档时间: |
|
| 查看次数: |
16319 次 |
| 最近记录: |