如何使用python将一个csv文件附加到另一个csv文件
我有两个.csv文件,需要加入新文件或将其中一个附加到另一个文件中: 文件A:如何使用python将一个csv文件附加到另一个csv文件,python,csv,Python,Csv,我有两个.csv文件,需要加入新文件或将其中一个附加到另一个文件中: 文件A: jan,feb,mar 80,50,52 74,73,56 文件B: 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 我用的是我能找
jan,feb,mar
80,50,52
74,73,56
文件B:
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):
在python中根本不是这样,但是有一个bash命令正好用于此:
paste-d','filea.csv fileb.csv
您将字符串传递给writerow
,因此它将迭代并用逗号分隔字符。你需要建立一个代表每一行的列表['Jan'、'Feb'、…、'Jun']
,并将其传递给writerow
。抱歉,我编辑了我的问题,没有意识到我已经收到了评论。非常感谢大家。@Meelah,你们的文件长度相等吗?fredtantini-谢谢,但我试过了,得到了完全相同的结果@Padraic-我尝试使用的文件长度相等,但我需要一些可以处理不同长度的文件,并且可能包含空白字段的文件。
jan,feb,mar,apr,may,jun
80,50,52,64,75,64
74,73,56,75,63,63
,,,77,88,99