pythoncsvreadercsvwriter

Is that possible to combine two csv files into one as mentiioned below


I am trying to combine csv file into one as below mentioned

input1:

Name,Age,Department
Birla,52,Welding
Rob,45,Furnace

input2:

YearofService,Audit
14,Y
8,N

My expected output :

Name,Age,Department,YearofService,Audit
Birla,52,Welding,14,Y
Rob,45,Furnace,8,N

My code :

with open('input1.csv','r') as i,open('input2.csv','r') as o:
      reader=csv.reader(i)
      fieldnames=reader.fieldnames
      reader1=csv.reader(o)
      fieldnames_1=reader1.fieldnames
      #here reading the fieldnames and combine csv file as 1:

I dont need to uuse python pandas.is that possible to achieve using csv library? help me on this. Instead of writing into sepearate ouput file,if its we ad the input to input1 is also fine


Solution

  • You can simply read both files at the same time and combine the rows to create a new one (or write over one of them). Here is one example on how you can do it, but you can adapt to your needs.

    import csv
    
    with open('input1.csv','r') as input1, open('input2.csv', 'r') as input2:
        with open('output.csv', 'w') as output:
    
            writer = csv.writer(output, lineterminator='\n')
    
            reader1 = csv.reader(input1)
            reader2 = csv.reader(input2)
    
            rows = []
            for row1, row2 in zip(reader1, reader2):
                rows.append(row1 + row2)
    
            writer.writerows(rows)
    

    Side note: don't forget that the best way to join CSVs are using common indexes, so the rows keep aligned. Python default CSV library is basic and ideally a better tool for dealing with them should be used, such as Pandas.