def _mergeFiles(key, chunkCount, outputFile, fields):
title()<EOL>files = [FileRecordStream('<STR_LIT>' % i) for i in range(chunkCount)]<EOL>with FileRecordStream(outputFile, write=True, fields=fields) as o:<EOL><INDENT>files = [FileRecordStream('<STR_LIT>' % i) for i in range(chunkCount)]<EOL>records = [f.getNextRecord() for f in files]<EOL>while not all(r is None for r in records):<EOL><INDENT>indices = [i for i,r in enumerate(records) if r is not None]<EOL>records = [records[i] for i in indices]<EOL>files = [files[i] for i in indices]<EOL>r = min(records, key=itemgetter(*key))<EOL>o.appendRecord(r)<EOL>index = records.index(r)<EOL>records[index] = files[index].getNextRecord()<EOL><DEDENT><DEDENT>for i, f in enumerate(files):<EOL><INDENT>f.close()<EOL>os.remove('<STR_LIT>' % i)<EOL><DEDENT>
Merge sorted chunk files into a sorted output file

    chunkCount - the number of available chunk files
    outputFile the name of the sorted output file

    _mergeFiles()