简体   繁体   中英

How to append one csv file to another with python

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'.

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

In case your files have the same length or at least contain blank fields:

filea.csv

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

fileb.csv

apr,may,jun
64,75,64
75,63,63
77,88,99

Script :

with open("filea.csv", "r") as source1, open("fileb.csv", "r") as source2, open("filec.csv","w") as dest:
    for line1, line2 in zip(source1, source2):
        dest.write(line1.strip()+','+line2)

If you need more compact version :

with open("filea.csv", "r") as source1, open("fileb.csv", "r") as source2, open("filec.csv","w") as dest:
    [dest.write(line1.strip()+','+line2) for line1, line2 in zip(source1, source2)]

Result (filec.csv):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM