I need to find a certain line in some output. I can do this, but then having found the right part of the output, I need to extract certain lines before that one.
for i, line in enumerate(lines):
target = str(self.ma3) # set target string
if target in line:
print i, line # this gets the correct line, I can stick it in a variable and do stuff with it
i = i - 4 # now I want the line 4 lines before the initial target line
print lines[i] # doesn't work, gives error: TypeError: 'generator' object has no attribute '__getitem__'
If anyone knows how to do this the help would be appreciated!
You need to use a list to have random access:
lines = list(lines)
# your code
A generator just feeds you items one at a time, and has no concept of "indexing", unlike a list.
Alternatively, if your file is very large and putting all of the lines into a list would be too expensive, you could extract 4 items at a time from the generator. That way, you would have access to the line four lines before your target line should you find it. You'd have to do some bookkeeping to make sure that you don't skip over any lines.