csv - Python: Concatenate two dictReader strings for header row -
i'm trying create header row in results file first file's header row plus second file's header row. example: legacy file header row: (column a, column b ...) mapping file header row: (column c, column d ...) , results file should contain: (column a, column b, column c, column d) separated out text each each column. i'm having trouble coming proper way concatenate two. can see below "+" not valid. header row first row in file. suggestions appreciated.
import csv open('legacyfile.csv', 'r') in_leg, open('mappingfile.csv', 'r') in_map, open('results.csv', 'wb') out_res: c1 = csv.dictreader(in_leg, delimiter=',', quoting=csv.quote_none, fieldnames=[]) c2 = csv.dictreader(in_map, delimiter=',', quoting=csv.quote_none, fieldnames=[]) #set headers , write header row output file headerlist1 = list(c1) headerlist2 = list(c2) c1.fieldnames = (headerlist1[0]) c2.fieldnames = (headerlist2[0]) #fieldnames = c1.fieldnames + c2.fieldnames #--> can't concatenate these print c1.fieldnames print c2.fieldnames c3 = csv.dictwriter(out_res, fieldnames=fieldnames) c3.writeheader() in_leg.close() in_map.close() out_res.close()
if @ structure of c1.fieldnames
, c2.fieldnames
, see formatted , typed like:
(pdb) c1.fieldnames {none: ['field1', 'field2', ..., 'fieldn']} (pdb) type(c1.fieldnames) <type 'dict'>
so can combine these 2 creating new dictionary object has key of none
, value of first set of fieldnames
+ second set. can use line:
fieldnames = {none: c1.fieldnames[none] + c2.fieldnames[none]}
to accomplish this.
then when write out dictionary, make sure use line:
c3 = csv.dictwriter(out_res, fieldnames=fieldnames[none])
instead. need pull list of names out of dictionary object.
let me know if works.
Comments
Post a Comment