比较两个CSV并将缺失值(在不同的行中)写入文件python

时间:2014-08-08 06:54:30

标签: python

我需要比较两个文件并将缺少的值写入另一个文件

File1.csv:

Monday, sports, swimming
Tuesday, study, running
Wednesday, jog, sprint
Thursday, nothing, Play

File2.csv:

Monday
Wednesday

output_File应为:

Tuesday, study, running
Thursday, nothing, Play

我尝试过:

import csv

f1 = file('C:\File1.csv', 'rb')
f2 = file('C:File2.csv', 'rb')
f3 = file('C:\output_file.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row for row in c2]
for hosts_row in c1:
    for master_row in masterlist:
        results_row = hosts_row
        if hosts_row[0] == master_row[0]:
                print results_row
                c3.writerow(results_row)

Output_file.csv:

Monday, sports, swimming
Wednesday, jog, sprint

2 个答案:

答案 0 :(得分:0)

import csv

f1 = file('C:\File1.csv', 'rb')
f2 = file('C:File2.csv', 'rb')
f3 = file('C:\output_file.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row[0] for row in c2]

for hosts_row in c1:
    if hosts_row[0] not in masterlist:
        print hosts_row
        c3.writerow(hosts_row)

答案 1 :(得分:0)

有点短而没有cvs(你实际上并不需要它):

file1 = [line.strip() for line in open('File1.csv')]
file2 = [line.strip() for line in open('File2.csv')]

with open('output_File.cvs', 'w') as f:
    for line in file1:
        if not line.split(',')[0] in file2:
            f.write(line + '\n')

编辑:您之间的单行爱好者可以用

替换循环
f.writelines('\n'.join(filter(lambda l: not l.split(',')[0] in file2, file1)))