简体   繁体   English

在Python中联接两个csv文件

[英]Joining two csv files in Python

I want to join two csv files into one like this: 我想将两个csv文件合并为一个:

**file 1:**
feb,55,1.23,..,..,0
mar,65,2.33,..,..,1

**file 2:**
feb,55,..,12,KL,..
mar,65,..,10,MN,.. 

so the output would be something like this: 所以输出将是这样的:

feb,55,1.23,12,KL,0
mar,65,2.33,10,MN,1

My following code snippet doesn't works: 我的以下代码段不起作用:

f1=[li.split(',') for li in open("file1.csv","r+")]
f2=[lj.split('\t') for lj in open("file2.csv","r+")]

def joinL(x,y):
    list=[]
    for n in x:
        for m in y:
            if n[0]==m[0]:
                list.append(m)
    return list

print joinL(f1,f2)

Could you please help Thanks! 您能帮忙吗,谢谢!

This works for me: 这对我有用:

with open('filename1', 'r') as fl1:
    f1 = [i.split(',') for i in fl1.read().split('\n')]

with open('filename2', 'r') as fl2:
    f2 = [i.split(',') for i in fl2.read().split('\n')]

f3 = [[a if b is None or b==len(b)*b[0] else b for a,b in map(None,x,y)] for x,y in zip(f1,f2)]

for i in f3:
    for j in i:
        print j,
    print

[OUTPUT]
feb,55,1.23,12,KL,0
mar,65,2.33,10,MN,1

Note, you had a minor mistake in your text. 请注意,您的文字有一个小错误。 It should be 2.33 not 2,33 . 应该是2.33而不是2,33

Here is EXACTLY the code I am using: 这也正是我使用的代码:

#my_script.py
with open('t1.txt', 'r') as fl1:
    f1 = [i.split(',') for i in fl1.read().split('\n')]

with open('t2.txt', 'r') as fl2:
    f2 = [i.split(',') for i in fl2.read().split('\n')]

f3 = [[a if b is None or b==len(b)*b[0] else b for a,b in map(None,x,y)] for x,y in zip(f1,f2)]

for i in f3:
    for j in i:
        print j,
    print

#t1.txt
feb,55,1.23,..,..,0
mar,65,2.33,..,..,1

#t2.txt
feb,55,..,12,KL,..
mar,65,..,10,MN,..

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

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