window.append(row)
if row[0] < window[-2][0]:
    window = collections.deque(sorted(window), maxlen=window_size)
for row in window:
    writer.writerow(row)
How to filter and sort stream of large text file in Python