简体   繁体   English

如何使用python将一个csv文件附加到另一个

[英]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: 我有两个.csv文件,我需要将它们加入一个新文件或将一个附加到另一个文件:

filea: FILEA:

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

fileb: 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 filea.csv

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

fileb.csv 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): 结果(filec.csv):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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