簡體   English   中英

如何使用python將一個csv文件附加到另一個

[英]How to append one csv file to another with python

我有兩個.csv文件,我需要將它們加入一個新文件或將一個附加到另一個文件:

FILEA:

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

FILEB:

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

我需要的是:

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

我得到的是:

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

我正在使用可以找到的最簡單的代碼。 我猜有點太簡單了:

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

如果有人能告訴我我在做什么錯,以及如何讓他們“水平”而不是“垂直”地添加,我將不勝感激。

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

如果文件的長度相同或至少包含空白字段:

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

劇本:

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)

如果您需要更緊湊的版本:

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

結果(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