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 cmp_nulls_last(*row_pair):
10
    def repl(val):
11
        if val == '': val = () # sorts > ''
12
        return val
13
    return cmp(*map(lambda row: map(repl, row), row_pair))
14

    
15
def main():
16
    col_nums = sys.argv[1:]
17
    if col_nums == []:
18
        raise SystemExit('Usage: '+sys.argv[0]+' col_num... <map >sorted_map')
19
    col_nums = map(int, col_nums) # 0-based
20
    
21
    # Sort map
22
    reader = csv.reader(sys.stdin)
23
    cols = reader.next()
24
    def get_sort_by(row): return by_idx(row, col_nums)
25
    rows = list(reader)
26
    rows.sort(lambda *row_pair: cmp_nulls_last(*map(get_sort_by, row_pair)))
27
    writer = csv.writer(sys.stdout)
28
    writer.writerow(cols)
29
    map(writer.writerow, rows)
30

    
31
main()
(47-47/58)