0

I have a script which opens a cvs and writes it out again (with a different name) without some columns I don't need.

source = outname
    with open(source, "rb") as source:
        rdr = csv.reader(source)
        with open("import2SFDC.csv", "wb") as result:
            wtr = csv.writer(result, quoting=csv.QUOTE_ALL)
            for r in rdr:
                wtr.writerow((r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10],
                            r[12], r[13], r[14], r[16], r[17], r[18], r[19], r[20], r[21],
                            r[22], r[23], r[24], r[25], r[26], r[27], r[28], r[29], r[33],
                            r[35], r[36], r[37], r[38], r[39], r[40], r[42], r[43], r[44],
                            r[46], r[47], r[48], r[49], r[50], r[51], r[52], r[53], r[54],
                            r[56], r[57], r[60], r[61], r[63], r[70], r[81], r[82]))

This works fine so far. I now would like to ADD a column with a header of "SFDCID". The value for this column should always (i.e. in all rows) be the value of arg.parse:

 parser.add_argument("SFDCID", type=str,
                        help="Salesforce ID of the Account the contact should be matched to")

So, I call the script with the SFDCID as an argument and this needs to be written as a column into the resulting csv file.

I'm quite new to python and was able to build the original script only because of the great help here, maybe someone can help me with this extension?

thanks

Andre

f0rd42
  • 1,429
  • 4
  • 19
  • 30

1 Answers1

1

You need to read the header, append your extra header to it and then write out your new file:

# These are the columns we will not write
skip = [11, 15, 30, 31, 32, 34, 41, 45, 55, 58, 59, 62]
skip += range(64, 70)
skip += range(71, 81)

with open('read.csv', 'r') as r, open('write.csv', 'w') as w:
    reader = csv.reader(r)
    writer = csv.writer(w, delimiter=',')
    header = next(reader)
    header.append('SFDCID') # Add the new column
    writer.writerow(header) # write out the new header
    for row in reader:
        new_row = [v for k,v in enumerate(row) if k not in skip]
        new_row.append('your value for SFDCID column')
        writer.writerow(new_row)
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • perfect, thanks a lot Burhan, that really works well. I now just need to "understand" in detail what it's doing, especially the for loop. – f0rd42 Feb 19 '15 at 12:59
  • Too quick. Skipping the columns not of interest seems to not work. all columns are written into the resulting csv. – f0rd42 Feb 19 '15 at 14:40
  • Hi Burhan. Have you had a chance to look into my last comment / question? Thanks – f0rd42 Feb 24 '15 at 14:05