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_cols = reader.next()
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
    map_0_cols = reader.next()
31
    if not map_0_cols[1] == map_1_cols[0]: raise SystemExit('Map error: '
32
        'Map 0 output column name doesn\'t match map 1 input column name')
33
    writer.writerow(maps.merge_mappings(map_0_cols, map_1_cols))
34
    for row in reader:
35
        if row[1] != '':
36
            try: out_row = map_1[row[1]]
37
            except KeyError:
38
                row[2] = '** No join mapping for '+row[1]+' ** '+row[2]
39
                row[1] = ''
40
            else: row = maps.merge_mappings(row, out_row)
41
        writer.writerow(row)
42

    
43
main()
(7-7/19)