tonemgub tonemgub - 1 year ago 129
Python Question

How to concatenate two columns and update the csv in python?

In Excel, I would be able to use something like this:


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

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

In Python here is what I have so far:

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 )

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.

Answer Source

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.


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:]

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download