user18175092
user18175092

Reputation:

Using an index to read files to a list

I'd like to read in files line by line based on a found index after some condition. Here's an example:

Cats=[]
Dogs=[]
Fish=[]


with open('Report.txt') as f:
    for index, record in enumerate(f):
            if 'Cat' in record:
                
                index=(index+1)

Now I have the index. Is it possible to start reading the file into a list from this index?

Upvotes: 1

Views: 1016

Answers (2)

Talha Tayyab
Talha Tayyab

Reputation: 27665

You can also use this package to go directly to the line number if you know the line number

import linecache
  
# extracting the 5th line
particular_line = linecache.getline('Report.txt', 4)
  
# print the particular line
print(particular_line)

Upvotes: 0

Chris
Chris

Reputation: 1321

You can keep track of whether you already met the condition using a boolean value, i.e. foundCat. Once you meet the condition, you can set the boolean to True, and check if either you met the condition or if the boolean is True. Here's an example:

cats = [] # Reserve uppercase for class names
foundCat = False

with open('Report.txt') as f:
    for index, record in enumerate(f):
        if 'Cat' in record:
             foundCat = True
        if foundCat:
             cats.append(record)               

You don't need to increment index as enumerate() already does that automatically.

Upvotes: 1

Related Questions