tags:

views:

74

answers:

2

merge two columns in a csv file

A: 

Here is an example, dont know your delimiter. if you want to write it to the same file you have to buffer the whole file first, modify the rows, then write it back to the same file.

 import csv
 for row in csv.reader(open('test.txt'),delimiter="\t"):
     print row[0]+row[1]
ebt
hi thnx a lot really.... just another small doubt.. wat if i wanna add a dot(.) between the 2 concatenated strings??
Anand
and how do i write this concatenated column to a new csv file??
Anand
A: 
    fin = open('file.csv', 'r+')
    fout = open('NEW.csv','w')
    for line in fin.xreadlines():
        new = line.replace(',', ' ', 1)
        fout.write (new)
    fin.close()
    fout.close()

Assuming that "file.csv" is the input, and "NEW.csv" is the output. Also the first comma is getting replaced by space. You can alter that by modifying

new = line.replace(',', ' ', 1)

and replacing the second argument with anything you want

poscaman
this will merge all the columns in the file... i wanna merge only 2 specific columns... say col[3] and column [10].. how do i do tht?? please help... please :(
Anand