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 os.path
6
import sys
7

    
8
sys.path.append(os.path.dirname(__file__)+"/../lib")
9

    
10
import maps
11

    
12
def main():
13
    try: _prog_name, map_1_path = sys.argv
14
    except ValueError:
15
        raise SystemExit('Usage: '+sys.argv[0]+' <map_0 map_1 [| '+sys.argv[0]
16
            +' map_2]... >joined_map')
17
    
18
    # Get map 1
19
    map_1 = {}
20
    stream = open(map_1_path, 'rb')
21
    reader = csv.reader(stream)
22
    map_1_in, map_1_out = reader.next()[:2]
23
    for row in reader:
24
        if row[0] != '': map_1[row[0]] = row
25
    stream.close()
26
    
27
    # Join map 1 to map 0
28
    reader = csv.reader(sys.stdin)
29
    writer = csv.writer(sys.stdout)
30
    cols = reader.next()
31
    if not cols[1] == map_1_in: raise SystemExit('Map error: '
32
        'Map 0 output column name doesn\'t match map 1 input column name')
33
    cols[1] = map_1_out
34
    writer.writerow(cols)
35
    for row in reader:
36
        if row[1] != '':
37
            try:
38
                new = map_1[row[1]]
39
                row[1] = new[1] # mapping
40
                row[2:] = maps.merge_rows(row[2:], new[2:]) # comments
41
            except KeyError:
42
                row[2] = '** No join mapping for '+row[1]+' ** '+row[2]
43
                row[1] = ''
44
        writer.writerow(row)
45

    
46
main()
(6-6/17)