PYTHON-根据colunm 1中的相同值合并CSV文件

时间:2018-01-08 03:59:40

标签: python csv merge

我有2个CSV文件,每个文件都有数千行,我想合并并输出到新文件(results.csv)。 我在这里看了其他答案,但现在需要帮助。

请注意: - 两个文件都没有标题 - 我不想使用PANDA

文件1(file.csv)包含:

  

041,2017111,50501342,20058987,200765893,PPP,PLUS,D,NSW

     

455,2017082,50513457,20068678,2004676768,BBB,LONG,A,NSW

     

178,2017976,50586866,20089765,2008886565,LLL,PLUS,D,QLD

文件2(file2.csv)包含:

  

019,0.000,20150907,20170308

     

041,0.000,20160806,20170504

     

455,147.533,20140402,20170506

预期(results.csv)输出:

  

041,2017111,50501342,20058987,200765893,PPP,PLUS,D,NSW,0.000,20160806,20170504

     

455,2017082,50513457,20068678,2004676768,BBB,LONG,A,NSW,147.533,20140402,20170506

因此,当第1列相同时,代码将进行排序和连接。

到目前为止,我已尝试过以下但输出格式错误:

f1 = open(file.csv', 'r')
f2 = open(file2.csv', 'r')
f3 = open('results.csv', 'w')

c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)

file2 = list(c2)

for file1_row in c1:
    row = 1
    found = False
    results_row = file1_row  
    for file2_row in file2:        
        x = file2_row[1:]
        if file1_row[0] == file2_row[0]:
            results_row.append(x)
            found = True
            break
    row += 1
    if not found:
        results_row.append('Not found')     
    c3.writerow(results_row)



f1.close()
f2.close()
f3.close()

任何帮助将不胜感激。 感谢

1 个答案:

答案 0 :(得分:0)

您可以使用zip

import csv
f1 = csv.reader(open('file1.csv'))
f2 = csv.reader(open('file2.csv'))
final_file = csv.writer(open('file_output.csv', 'a'))
final_file.writerows([a+b for a, b in zip(f1, f2)])