我有两个.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
如果有人能告诉我自己做错了什么以及如何让他们水平追加,我将非常感激。而不是'垂直'。
答案 0 :(得分:1)
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]))
答案 1 :(得分: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