Reputation: 97
So I want to make this script look for a word, which you can determine, and its line number. I want it to print out the text in this line and the two following ones. How do I code the last part (print the next three lines)?
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)
Upvotes: 1
Views: 1326
Reputation: 8260
Yet another approach with not found
error handling:
with open('file.txt', 'r') as f:
lines = [line.strip() for line in f.readlines()]
try:
i = lines.index(input('Enter service: '))
for j in range(i, i+3):
try:
print(lines[j])
except IndexError:
pass
except ValueError:
print('Service not found!')
Upvotes: 1
Reputation: 56
There could be a better solution but this is a bit more flexible with a nigher amount of following rows.
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
Upvotes: 1
Reputation: 680
There are some corner cases that you did not mention.
If there's only one matching, or there won't be any matching in the lines you print right after, then you can use a single counter
def search_passwords():
file = open("D:\\Libaries\\Documents\\resources_py\\pw.txt", "r")
print()
search = input("Enter service: ")
print()
counter = 0
for line in file:
if counter > 0:
counter -= 1
print(line)
if search in line:
counter = 2
print(line)
However, this will double print the lines if the following lines containing the searching word. You can of course make the second if
elif
, but then it will just ignore the following matching pattern.
And, if you only need the first or only appearance, you should break out of the loop once you print everything, not read the whole file.
Just like I said, you need to know the expected behavior and the requirement better, to write a solid program.
Upvotes: 1