python search a string in a text file and copy a block
Question: I have this text file names.txt

    
    
    Daniel
    Sam
    Sameer
    Code
    Print
    Alpha
    Bravo
    Charlie
    

and I want to search it for string "Alpha" and copy the line "alpha" and the
previous 100 lines then write"append" it to file result.txt

    
    
     with open(names.txt) as g:
        lines = (g.readlines())
        for line in lines:
            if "{0}".format("Alpha") in line:
              ????????????
    

I writed this code and stopped here , any one could help ?


Answer: Probably the easiest way to do this is to maintain a list of the last 100
lines you've read, then output them to your `result.txt` file if the current
line is `'Alpha'`:

    
    
    limit = 100
    prev_items = []
    
    # Open file and iterate over lines.
    with open('names.txt') as f:
        for line in f:
            # Add the current line to the list.
            prev_items.append(line)
            # Reduce the list to its newest elements.
            prev_items = prev_items[-limit:]
    
            # If the current line is 'Alpha', we don't need to read any more.
            if line == 'Alpha':
               break
    
    # Append prev_items to the results file.
    with open('results.txt', 'a') as f:
        f.write('\n'.join(prev_items))
    

Or, if you're happy to use a collection other than `list`, use a
[`deque`](https://docs.python.org/2/library/collections.html#collections.deque):

    
    
    from collections import deque
    
    limit = 100
    prev_items = deque(maxlen=limit)
    
    # Open file and iterate over lines.
    with open('names.txt') as f:
        for line in f:
            # Add the line to the deque.
            prev_items.append(line)
    
            # If the current line is 'Alpha', we don't need to read any more.
            if line == 'Alpha':
               break
    
    # Append prev_items to the results file.
    with open('results.txt', 'a') as f:
        f.write('\n'.join(prev_items))
    

