首页 > 解决方案 > 如何打印接下来的几行

问题描述

所以我想让这个脚本寻找一个你可以确定的单词,以及它的行号。我希望它打印出这一行中的文本以及以下两个文本。如何编码最后一部分(打印接下来的三行)?

def search_passwords():
    file = open("D:\\Libaries\\Documents\\resources_py\\pw.txt",  "r")
    print()
    search = input("Enter service: ")
    print()   
    for line in file:
        if search in line:  
           print(the next three lines)

标签: pythonpython-3.x

解决方案


可能有一个更好的解决方案,但是这会更灵活,有更多的后续行。

def search_passwords():
    file = open("D:\\Libaries\\Documents\\resources_py\\pw.txt",  "r")
    print()
    search = input("Enter service: ")
    print()   
    counter = 3
    found = False
    for line in file:
        if search in line:  
           found = True
        if found:
            if counter > 0: 
                counter -= 1
                print(line, counter)
            if counter == 0:
                break

推荐阅读