Project

General

Profile

1 157 aaronmk
#!/usr/bin/env python
2
# Sorts a spreadsheet based on a column
3
4
import csv
5
import sys
6
7 189 aaronmk
def by_idx(list_, idxes): return [list_[i] for i in idxes]
8
9 157 aaronmk
def main():
10 189 aaronmk
    col_nums = sys.argv[1:]
11
    if col_nums == []:
12
        raise SystemExit('Usage: '+sys.argv[0]+' col_num... <map >sorted_map')
13
    col_nums = map(int, col_nums) # 0-based
14 157 aaronmk
15
    # Sort map
16
    reader = csv.reader(sys.stdin)
17
    cols = reader.next()
18 189 aaronmk
    def get_sort_by(row): return by_idx(row, col_nums)
19 157 aaronmk
    rows = list(reader)
20 189 aaronmk
    rows.sort(lambda *rows: cmp(*map(get_sort_by, rows)))
21 157 aaronmk
    writer = csv.writer(sys.stdout)
22
    writer.writerow(cols)
23
    map(writer.writerow, rows)
24
25
main()