textfile: copy between 2 keywords

Jussi Piitulainen harvesting at makes.email.invalid
Thu Sep 10 09:47:39 EDT 2015


Gerald writes:

> Hey,
>
> is there a easy way to copy the content between 2 unique keywords in a
> .txt file?
>
> example.txt
>
> 1, 2, 3, 4
> #keyword1
> 3, 4, 5, 6
> 2, 3, 4, 5
> #keyword2 
> 4, 5, 6 ,7

Depending on your notion of easy, you may or may not like itertools.
The following code gets you the first keyword and the lines between but
consumes the second keyword. If I needed more control, I'd probably
write what Steven D'Aprano wrote but as a generator function, to get the
flexibility of deciding separately what kind of copy I want in the end.

And I'd be anxious about the possibility that the second keyword is not
there in the input at all. Steven's code and mine simply take every line
after the first keyword in that case. Worth a comment in the code, if
not an exception. Depends.

Code:

from itertools import dropwhile, takewhile
from sys import stdin

def notbeg(line): return line != '#keyword1\n'
def notend(line): return line != '#keyword2 \n' # sic!

if __name__ == '__main__':
    print(list(takewhile(notend, dropwhile(notbeg, stdin))))

Output with your original mail as input in stdin:

['#keyword1\n', '3, 4, 5, 6\n', '2, 3, 4, 5\n']



More information about the Python-list mailing list