Extract Values between two strings in a text file using python

后端 未结 7 1423
闹比i
闹比i 2020-11-29 08:27

Lets say I have a Text file with the below content

fdsjhgjhg
fdshkjhk
Start
Good Morning
Hello World
End
dashjkhjk
dsfjkhk

Now I need to wr

7条回答
  •  囚心锁ツ
    2020-11-29 08:57

    Using itertools.dropwhile, itertools.takewhile, itertools.islice:

    import itertools
    
    with open('data.txt') as f, open('result.txt', 'w') as fout:
        it = itertools.dropwhile(lambda line: line.strip() != 'Start', f)
        it = itertools.islice(it, 1, None)
        it = itertools.takewhile(lambda line: line.strip() != 'End', it)
        fout.writelines(it)
    

    UPDATE: As inspectorG4dget commented, above code copies over the first block. To copy multiple blocks, use following:

    import itertools
    
    with open('data.txt', 'r') as f, open('result.txt', 'w') as fout:
        while True:
            it = itertools.dropwhile(lambda line: line.strip() != 'Start', f)
            if next(it, None) is None: break
            fout.writelines(itertools.takewhile(lambda line: line.strip() != 'End', it))
    

提交回复
热议问题