How to concatenate two columns and update the csv in python?
<p>In Excel, I would be able to use something like this:</p>

<pre><code>=CONCATENATE(A1," ",B1) 
</code></pre>

<p>(User flood fill's this down the spreadsheet, and then simply deletes A and B, lastly you move results to A)</p>

<p>End Result is expected to have A and B columns merged into one column (A) and separated by one space.</p>

<p>In Python here is what I have so far:</p>

<pre><code>import csv
with open("test.csv","rb") as source:
    rdr= csv.reader( source )
    with open("result","wb") as result:
        wtr= csv.writer( result )
        for r in rdr:
            print("Adding merged COL1/COL2 into one column for every row...")
            wtr.writerow(r+[r[0] + ' ' + r[1]])
            print("Deleting COL1/COL2 columns from every row...")
            del r[0]
            del r[0]
            wtr.writerow( r )
    result.close();
</code></pre>

<p>Although, the above code does properly merge two columns and append a column to the end of the file, it does not properly delete the first two rows once it is finished, I believe this is because wtr.writerow has already been called. Also, I am unsure how to move the column to the left (back to A), since it always appends to the end.</p>

<p>So every row you're reading from (and writing to) csv is a list, right? So take another step or two and create the list you want, then write it.</p>

<p>e.g.</p>

<pre><code>import csv
with open('test.csv') as f:
    reader = csv.reader(f)
    with open('output.csv', 'w') as g:
        writer = csv.writer(g)
        for row in reader:
            new_row = [' '.join([row[0], row[1]])] + row[2:]
            writer.writerow(new_row)
</code></pre>

<p>Also, I doubt you need to read/write binary ('rb', 'wb') from a csv.</p>

python csv