Combining Csv Files Column-wise
Suppose I have two CSV files called A and B in Python. A's head looks like: headerNameA1,headerNameA2 1.12412424,1 1,1 1,1 1,1 B's head looks like: headerNameB1,headerNameB2
Solution 1:
You can consume one line at a time from both files, concatenating them together and writing to your outfile. The csv
module makes things a bit cleaner.
import csv
withopen('A','rb') as f1, open('B','rb') as f2, open('out.csv','wb') as w:
writer = csv.writer(w)
r1,r2 = csv.reader(f1),csv.reader(f2)
whileTrue:
try:
writer.writerow(next(r1)+next(r2))
except StopIteration:
break
And as @RogerPate points out, you can make this slicker with itertools.izip
(just zip
if you're in python3)
from itertools import izip
import csv
withopen('A','rb') as f1, open('B','rb') as f2, open('out.csv','wb') as w:
writer = csv.writer(w)
for r1,r2 in izip(csv.reader(f1),csv.reader(f2)):
writer.writerow(r1+r2)
Post a Comment for "Combining Csv Files Column-wise"