Project

General

Profile

1
#!/usr/bin/env python
2
# Sorts a spreadsheet based on a column
3

    
4
import csv
5
import sys
6

    
7
def by_idx(list_, idxes): return [list_[i] for i in idxes]
8

    
9
def main():
10
    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
    
15
    # Sort map
16
    reader = csv.reader(sys.stdin)
17
    cols = reader.next()
18
    def get_sort_by(row): return by_idx(row, col_nums)
19
    rows = list(reader)
20
    rows.sort(lambda *rows: cmp(*map(get_sort_by, rows)))
21
    writer = csv.writer(sys.stdout)
22
    writer.writerow(cols)
23
    map(writer.writerow, rows)
24

    
25
main()
(12-12/14)