Reputation:
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
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
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