我试图在比赛后打印下3行
例如输入是:
Testing
Result
test1 : 12345
test2 : 23453
test3 : 2345454
所以我试图在文件中搜索"结果" 字符串并从中打印下3行:
输出将是: -
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
如何获得我想要的输出,请帮助
答案 0 :(得分:2)
首先,您需要检查文本是否在line
(不在fileobj f
中),并且您可以利用islice
从{{1}开始接下来的3行并打印它们,例如:
f
循环将从三行打印后的行继续。如果您不希望这样 - 请在from itertools import islice
with open(filename) as f:
for line in f:
if 'Result' in line:
print(''.join(islice(f, 3)))
内添加break
。
答案 1 :(得分:1)
您正在测试(和打印)“f”而不是“line”。小心一点。 'f'是文件指针,line有您的数据。
with open(filename, 'r+') as f:
line = f.readline()
while(line):
if "Benchmark Results" in line:
# Current line matches, print next 3 lines
print(f.readline(),end="")
print(f.readline(),end="")
print(f.readline(),end="")
line = f.readline()
答案 2 :(得分:0)
它正在等待文件中的第一个“结果”,然后输出其余的输入:
=MeterReadings!K"x"-MeterReadings!K"y"
如果你想在前三次打印后结束,你可以添加变量import re, sys
bool = False
with open("input.txt", 'r+') as f:
for line in f:
if bool == True:
sys.stdout.write(line)
if re.search("Result",line): #if it should match whole line, than it is also possible if "Result\n" == line:
bool = True
并更改这部分代码(例如这样):
cnt = 0
答案 3 :(得分:0)
with open('data', 'r') as f:
lines = [ line.strip() for line in f]
# get "Result" index
ind = lines.index("Result")
# get slice, add 4 since upper bound is non inclusive
li = lines[ind:ind+4]
print(li)
['Result', 'test1 : 12345', 'test2 : 23453', 'test3 : 2345454']
or as exercise with regex:
import re
with open('data', 'r') as f:
text = f.read()
# regex assumes that data as shown, ie, no blank lines between 'Result'
# and the last needed line.
mo = re.search(r'Result(.*?\n){4}', text, re.MULTILINE|re.DOTALL)
print(mo.group(0))
Result
test1 : 12345
test2 : 23453
test3 : 2345454
答案 4 :(得分:0)
我建议打开文件并将其内容分成行,将结果分配给变量,这样您就可以更舒适地操作数据:
file = open("test.txt").read().splitlines()
然后你可以检查哪一行包含字符串"结果",并打印以下三行:
for index, line in enumerate(file):
if "Result" in line:
print(file[index+1:index+4])