import sys, csv remote = sys.argv[1] local = sys.argv[2] inpath = sys.argv[3] outpath = sys.argv[4] def parse_header(line): return next(csv.reader([line])) R = parse_header(remote) L = parse_header(local) n_remote = len(R) # Build mapping from remote positions -> local index or None (insert) # If remote column matches a later local column, drop the intervening local columns. mapping = [] insert_positions = set() li = 0 for i, rf in enumerate(R): if li < len(L) and rf == L[li]: mapping.append(li) li += 1 else: # look ahead in local for rf found = None for j in range(li + 1, len(L)): if L[j] == rf: found = j break if found is not None: # drop local columns li..found-1, map this remote to found mapping.append(found) li = found + 1 else: # remote column is new -> insert mapping.append(None) insert_positions.add(i + 1) def fmt_field(s): if s is None: s = '' # quote only when csv rules require it if (',' in s) or ('"' in s) or s.startswith(' ') or s.endswith(' '): return '"' + s.replace('"', '""') + '"' return s with open(inpath, newline='') as inf, open(outpath, 'w', newline='') as outf: reader = csv.reader(inf) for row in reader: out_fields = [] for m in mapping: if m is None: # insert empty unquoted cell -> produces ,, in CSV out_fields.append('') else: val = row[m] if m < len(row) else '' out_fields.append(fmt_field(val)) outf.write(','.join(out_fields) + '\n')