python - 如何打印接下来的几行
问题描述
所以我想让这个脚本寻找一个你可以确定的单词,以及它的行号。我希望它打印出这一行中的文本以及以下两个文本。如何编码最后一部分(打印接下来的三行)?
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)
解决方案
可能有一个更好的解决方案,但是这会更灵活,有更多的后续行。
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
推荐阅读
- sql - CASE 错误地返回 true
- angularjs - 升级以在 AngularJS 的指令中使用 $onInit
- udp - Google 计算引擎连接到本地 UDP 端口
- selenium - 如何在电子邮件(Outlook)正文中为测试执行摘要生成 HTML 表
- c# - 我们可以保留从.NET 创建的## 表,直到我从另一个过程执行我的代码?
- sql - 编写一个循环,引入两种不同的日期格式
- python - 如何在会话 SQLAlchemy 中获取对象的父对象
- cmake - 如何在 xxxConfigVersion.cmake 中跳过 32/64 位检查
- linux - 如何增加 xdiskusage 中的字体大小?
- php - 策略模式上下文中的多种策略