【问题标题】:Joining two csv files in Python在 Python 中加入两个 csv 文件
【发布时间】:2025-11-28 20:15:02
【问题描述】:

我想像这样将两个 csv 文件合并为一个:

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

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

所以输出会是这样的:

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

我的以下代码 sn-p 不起作用:

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)

你能帮忙吗 谢谢!

【问题讨论】:

  • 如果我理解正确,在一种情况下你有“1.23”,而在另一种情况下,融合后在同一个地方有“2”和“33”,我认为不知道这种情况何时发生。是否有可能“2”、“33”实际上是“2.33”
  • 是啊,对不起,现在是 2.33

标签: python csv merge


【解决方案1】:

这对我有用:

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

请注意,您的文字中有一个小错误。应该是2.33 而不是2,33

这是完全我正在使用的代码:

#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,..

【讨论】:

  • 这是一个错误仍然是一个问题:-)
  • 它给了我 IndexError: string index out of range
  • @Doublexo,它对我来说很好用。您确定您没有更改任何代码吗?
  • 这正是我写的:with open('log1.csv', 'r') as fl1: f1 = [i.split(',') for i in fl1.read() .split('\n')] with open('log2.csv', 'r') as fl2: f2 = [i.split(',') for i in fl2.read().split('\n ')] j=[[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 k in j: for l in k: print l print
  • @Doublexo,您是否记下您在文本文件中出现的错误,我已在回答中显示。另外,您是否将上面的两个文件名替换为您的适当文件名?