4 ms·
Perhaps a `DictWriter` would simplify things: import csv import sys filename = "example.csv" sort_by = "index" reverse = True
by cmdlineluser 4y ago
Perhaps a `DictWriter` would simplify things:
import csv
import sys
filename = "example.csv"
sort_by = "index"
reverse = True
with open(filename, newline="") as f:
reader = csv.DictReader(f)
writer = csv.DictWriter(sys.stdout, fieldnames=reader.fieldnames)
writer.writeheader()
writer.writerows(sorted(reader, key=lambda row: int(row[sort_by]), reverse=reverse))
- gabrielsroka 4y agoI thought about that but 1) it seemed like cheating to write to standard out, 2) you're assuming that the column to sort by is an integer whereas I broke that code up a little bit. But yours has the advantage of being able to support more complex CSVs.