I imagine the change in number of dashes (4 in the input, sometimes 4 and sometimes 3 in the output) is an error and not actually desired (since no algorithm is even hinted at, to explain how many dashes are to be output on different occasions).
I would structure the task in terms of reading and yielding one block of lines at a time:
def readbyblock(f):
while True:
block = []
for line in f:
if line = '----\n': break
block.append(line)
if not block: break
yield block
so that the (selective) output can be neatly separated from the input:
with open('infile.txt') as fin:
with open('oufile.txt', 'w') as fou:
for block in readbyblock(fin):
if 'extractme\n' in block:
fou.writelines(block)
fou.write('----\n')
This is not optimal, performance-wise, if the blocks are large, since it has a separate loop on all lines in the block implied in the if
clause. So, a good refactoring might be:
def selectivereadbyblock(f, marker='extractme\n'):
while True:
block = []
extract = False
for line in f:
if line = '----\n': break
block.append(line)
if line==marker: extract = True
if not block: break
if extract: yield block
with open('infile.txt') as fin:
with open('oufile.txt', 'w') as fou:
for block in selectivereadbyblock(fin):
fou.writelines(block)
fou.write('----\n')
Parameterizing the separators (now hard-coded as '----\n' for both input and output) is another reasonable coding tweak.