with open('input_file', 'r') as f:
    with open('output.dat', 'a') as media:
        write_to_file = False
lines = f.readlines()
for line in lines:
    if line.startswith('InvNo:'):
        first_line = 'IN ' + line.split()[1] + '\n'
if line.startswith('Media:'):
    write_to_file = True
if line.startswith('~EOR~') and write_to_file:
    url = 'blabla'
media.write(first_line + url + '\n' + '**\n')
write_to_file = False
first_line = ''
Управление потоком Python с флагом?