sorted_files = []
nbytes = 1 << 20
for lines in iter(partial(sys.stdin.readlines, nbytes), []):
    lines.sort(key=second_column)
f = TemporaryFile('w+')
f.writelines(lines)
f.seek(0)
sorted_files.append(f)
sys.stdout.writelines(merge(key=second_column, *sorted_files))
for f in sorted_files:
    f.close()
Sorting text file by using Python