with open('input.txt') as input_file:
    for chunk_number in count(1):
        sorted_chunk = sorted(islice(input_file, 50000))
if not sorted_chunk:
    break
chunk_name = 'chunk_{}.chk'.format(chunk_number)
chunk_names.append(chunk_name)
with open(chunk_name, 'w') as chunk_file:
    chunk_file.writelines(sorted_chunk)
with ExitStack() as stack:
    pass
Sort a big file with Python heapq.merge