Zamdokie
Zamdokie

Reputation: 11

Python: Reading Files // getting a line + line after

I am opening and reading a specific file and looking at its data. I have a specific line that is in my data and I want to print THAT line plus the line that comes next. Any ideas on how I might be able to access the second line? Here is my code thus far:

file = input("Enter a file: ")
f = open(file)
counter = 0
locked_record = "***STUDENT'S CURRENT FM RECORD LOCKED***"
for student in f:
    student = student.strip()
    counter += 1
    if student == locked_record:
        print (counter, student)**

Here is an example of my output:

91 ***STUDENT'S CURRENT FM RECORD LOCKED***
93 ***STUDENT'S CURRENT FM RECORD LOCKED***

I want to be able to access counts 92 and 94, but obviously, in a perfect world, I wouldn't know where exactly the count is that I want to access.

Upvotes: 0

Views: 27

Answers (1)

Samwise
Samwise

Reputation: 71512

If the file is small enough to read into memory, an easy option is to turn it into a list and then zip each line with the following line:

with open(input("Enter a file: ")) as f:
    students = [line.strip() for line in f]

for a, b in zip(students, students[1:]):
    if a == "***STUDENT'S CURRENT FM RECORD LOCKED***":
        print(a, b, sep="\n")

Upvotes: 1

Related Questions