How to append one csv file to another with python
Question: I have two .csv files that I need to either join into a new file or append one
to the other:

filea:

    
    
    jan,feb,mar
    80,50,52
    74,73,56
    

fileb:

    
    
    apr,may,jun
    64,75,64
    75,63,63
    

What I need is:

    
    
    jan,feb,mar,apr,may,jun
    80,50,52,64,75,64
    74,73,56,75,63,63
    

What I'm getting:

    
    
    jan,feb,mar
    80,50,52
    74,73,56
    apr,may,jun
    64,75,64
    75,63,63
    

I'm using the simplest code I can find. A bit too simple I guess:

    
    
    sourceFile = open('fileb.csv', 'r')
    data = sourceFile.read()
    with open('filea.csv', 'a') as destFile:
        destFile.write(data
    

I'd be very grateful if anyone could tell me what I'm doing wrong and how to
get them to append 'horizontally' instead of 'vertically'.


Answer: 
    from itertools import izip_longest
    with open("filea.csv") as source1,open("fileb.csv")as source2,open("filec.csv","a") as dest2:
        zipped = izip_longest(source1,source2) # use izip_longest which will add None as a fillvalue where we have uneven length files
        for line in zipped:
            if line[1]: # if we have two lines to join
                dest2.write("{},{}\n".format(line[0][:-1],line[1][:-1]))
            else: # else we are into the longest file, just treat line as a single item tuple
                 dest2.write("{}".format(line[0]))
    

