簡體   English   中英

如何在python中打印下一行

[英]How to print next line in python

我正在嘗試在比賽后打印接下來的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

我如何獲得所需的輸出,請幫助

首先,您需要檢查文本是否在該line (而不是在fileobj f ),然后可以使用islicef islice下3行並進行打印,例如:

from itertools import islice

with open(filename) as f:
    for line in f:
        if 'Result' in line:
            print(''.join(islice(f, 3)))

循環將在打印三張記錄后從該行繼續。 如果你不想這樣-在if里面放一點break

您正在測試(並打印)“ f”而不是“ line”。 請注意這一點。 “ f”是文件指針,行包含您的數據。

  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()

我建議打開文件並將其內容分成幾行,將結果分配給變量,以便您可以更舒適地操作數據:

file = open("test.txt").read().splitlines()

然后,您可以檢查哪一行包含字符串“ Result”,並打印以下三行:

for index, line in enumerate(file):
    if "Result" in line:
        print(file[index+1:index+4])

它正在等待文件中的第一個“結果”,然后打印其余輸入:

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

如果要在前3次打印后結束,可以添加變量cnt = 0並更改這部分代碼(例如,以這種方式):

        if bool == True:
            sys.stdout.write(line)
            cnt = cnt+1
            if cnt == 3:
                break
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM