I need to search a debug file for a specific string or error and then, once it's found, look up the file by 6 lines and then print whatever that line 6 above has in it.
import linecache
file = "/file.txt"
fh = open("/file.txt", "r")
lookup = 'No Output'
with fh as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
numUp = num + 6
new = linecache.getline(file, numUp)
print new
I tried adding doing something along the lines of "num += 6" whenever I find "The term I need to search" but my output is either blank or I receive this error:
File "testRead.py", line 12
print new
^
IndentationError: unexpected indent
If there's also another way to do "search, then scan up n-lines, then print/return" in a way that's line by line, that'd be great to know as well because the files I'll be working with vary greatly in size.
I upped an example file of some of the things I typically see: http://pastebin.com/mzvCfZid Any time I hit the string "(Err: No Output)", I need to find its associated ID, which is the number 6 lines above the error. So "No Output is what I'd need to search for.
::Edit::
You want the functionality of a deque
:
>>> from collections import deque
>>>
>>> lines = deque(maxlen = 7)
>>> for i in range(35):
... lines.append(i)
...
>>> print lines
# Note your 6 lines earlier would be lines[0] here.
deque([28, 29, 30, 31, 32, 33, 34], maxlen=7)