Add a new column to a csv file in python
<p>I am trying to add a column to a csv file that combines strings from two other columns. Whenever I try this I either get an output csv with only the new column or an output with all of the original data and not the new column. </p>

<p>This is what I have so far:</p>

<pre><code>with open(filename) as csvin:
    readfile = csv.reader(csvin, delimiter=',')
    with open(output, 'w') as csvout:
        writefile = csv.writer(csvout, delimiter=',', lineterminator='\n')
        for row in readfile:
            result = [str(row[10]) + ' ' + str(row[11])]
            writefile.writerow(result)
</code></pre>

<p>Any help would be appreciated.</p>

<p>Each row is read as a list, so you can append to it by adding another list (e.g. the new column value).  Your current code is simply writing the new column value.</p>

<pre><code>with open('data.csv') as fin, open('out.csv', 'wb') as fout:
    reader = csv.reader(fin)
    writer = csv.writer(fout)
    for row in reader:
        new_col_value = [str(row[10]) + ' ' + str(row[11])]
        writer.writerow(row + new_col_value)
</code></pre>

python python-2.7 csv