Project

General

Profile

1
#!/usr/bin/env python
2
# Inner-joins two map spreadsheets A->B and B->C to A->C
3

    
4
import csv
5
import sys
6

    
7
def main():
8
    try: _prog_name, map_1_path = sys.argv
9
    except ValueError:
10
        raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]
11
            +' map_2]... >joined_map')
12
    
13
    # Get map 1
14
    map_1 = {}
15
    stream = open(map_1_path, 'rb')
16
    reader = csv.reader(stream)
17
    map_1_in, map_1_out = reader.next()[:2]
18
    for row in reader:
19
        if row[1] != '': map_1[row[0]] = row[1]
20
    stream.close()
21
    
22
    # Join map 1 to map 0
23
    reader = csv.reader(sys.stdin)
24
    writer = csv.writer(sys.stdout)
25
    cols = reader.next()
26
    if not cols[1] == map_1_in: raise SystemExit('Map error: '
27
        'Map 0 output column name doesn\'t match map 1 input column name')
28
    cols[1] = map_1_out
29
    writer.writerow(cols)
30
    for row in reader:
31
        try: row[1] = map_1[row[1]]
32
        except KeyError: continue # skip row
33
        writer.writerow(row)
34

    
35
main()
(4-4/14)