Skip to content

Instantly share code, notes, and snippets.

@Averroes
Created April 10, 2015 14:09
Show Gist options
  • Save Averroes/78016bff7f61f2e0eb11 to your computer and use it in GitHub Desktop.
Save Averroes/78016bff7f61f2e0eb11 to your computer and use it in GitHub Desktop.
keeping the last n items
from collections import deque
def search(lines, pattern, history=5):
previous_lines = deque(maxlen=history)
for line in lines:
if pattern in line:
yield line, previous_lines
previous_lines.append(line)
# Example use on a file
if __name__ == '__main__':
with open('somefile.txt') as f:
for line, prevlines in search(f, 'python', 5):
for pline in prevlines:
print(pline, end='')
print(line, end='')
print('-'*20)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment